【发布时间】:2020-12-06 18:06:07
【问题描述】:
我正在尝试编写一个程序,该程序将读取从终端运行程序时调用的 .txt 文件。
使用的命令将是;
$ ./myexecutable input.txt
我的程序和 input.txt 在同一个目录下。到目前为止我的代码如下
#include <string>
#include <fstream>
using namespace std;
int main(int argc , char* argv[]){
string temp = "here";
string filename = argv[1];
ifstream myFile (filename);
myFile.open(filename);
if (myFile.is_open()){
while (getline (myFile, temp)){
cout << temp << endl;
myFile.close();
}
} else {
cout <<< "You have Entered Wrong File Name" << endl;
}
cout << "do with the simple program" << endl;
return 1;
};
但我得到的输出只是
file opened, do with the simple program
我对 fstream 不是很熟悉,所以不知道我哪里出错了。我按照他们的教程找到了here。 但显然我做错了什么。
感谢您的帮助。
【问题讨论】:
-
让
myFile.close();退出循环。您不想在阅读 1 行后关闭文件。您可以完全删除该行。当文件超出范围时,流将关闭文件。结果,我投票关闭了一个错字。 -
如果这确实是您正在使用的代码,我希望您文件的第一行是
file opened,。