【问题标题】:fstring not reading from .txt filefstring 未从 .txt 文件中读取
【发布时间】: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,

标签: c++ fstream iostream


【解决方案1】:

这是更正后的代码!! 你打开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;
    };

【讨论】:

  • 您仍然有我在第一条评论中提到的myFile.close(); 错误。
  • 看对方近身
猜你喜欢
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
相关资源
最近更新 更多