[英]How to read a .txt file in C++
We have this .txt that has this inside 我们有里面有这个.txt
PR-ATT-2 Sep 5 2018 Dec 15 2020
LE-GE-3 Oct 15 2019 Jan 20 2021
With our code, we're trying to set the first line to a string 通过我们的代码,我们试图将第一行设置为字符串
#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;
}
This returns nothing. 这什么也不会返回。 But if the code looks like this
但是如果代码看起来像这样
#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;
}
This returns "Hello my name is Alejandro, and my favorite word is pneumonoultramicroscopicsilicovolcanoconiosis PR-ATT-2 Sep 5 2018 D". 这将返回“您好,我叫亚历杭德罗,我最喜欢的词是肺炎微显微镜术硅肺炎PR-ATT-2 Sep 5 2018 D”。
We can not figure out for the life of us what is going on. 我们无法为我们的生活弄清楚发生了什么事。
We changed it to a while loop that prints the line until the end of the file, and that gave us our intended output. 我们将其更改为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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.