我们有一个.txt,里面有这个
PR-ATT-2 Sep 5 2018 Dec 15 2020
LE-GE-3 Oct 15 2019 Jan 20 2021在我们的代码中,我们尝试将第一行设置为字符串
#include <string>
#include <array>
#include <cstdlib>
#include <fstream>
#include <istream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
ifstream projin;
projin.open(argv[1], ios::in);
// Making sure the file opened correctly
if ((projin.is_open()) == false) {
cout << "There was an error opening the file";
return 1;
} else {
string projectline;
getline(projin, projectline);
cout << projectline << " ";
projin.close();
return 2;
}
return 0;
}这不会返回任何内容。但是如果代码看起来像这样
#include <string>
#include <array>
#include <cstdlib>
#include <fstream>
#include <istream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
ifstream projin;
projin.open(argv[1], ios::in);
// Making sure the file opened correctly
if ((projin.is_open()) == false) {
cout << "There was an error opening the file";
return 1;
} else {
string projectline;
getline(projin, projectline);
cout << "Hello my name is Alejandro, and my favorite word is
pneumonoultramicroscopicsilicovolcanoconiosis " << projectline << " ";
projin.close();
return 2;
}
return 0;
}这返回“您好,我的名字是Alejandro,我最喜欢的词是肺显微镜硅火山柯萨奇病PR-ATT-2 Sep 5 2018 D”。
我们这一生都搞不清楚到底发生了什么。
发布于 2018-09-23 07:14:41
我们将其更改为while循环,该循环打印该行直到文件末尾,这给出了我们想要的输出。
ifstream projin;
projin.open(argv[1], ios::in);
// Making sure the file opened correctly
if ((projin.is_open()) == false) {
cout << "There was an error opening the file";
return 1;
} else {
string projectline;
while (getline(projin, projectline)) {
cout << projectline << endl;
}
projin.close();
return 2;
}https://stackoverflow.com/questions/52461529
复制相似问题