问题描述
我正在尝试编写一个程序,该程序将读取从终端运行该程序时调用的.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
!
此语句中的第一次ifstream myFile (filename);
此语句中的第二次-myFile.open(filename);
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc,char* argv[]){
string temp = "here";
string filename = argv[1];
ifstream myFile (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;
};