【问题标题】:Cannot read input file using ifstream c++无法使用 ifstream c++ 读取输入文件
【发布时间】:2017-11-15 07:38:35
【问题描述】:

我有一个输入文件“abc.txt”,其中每一行都包含用“,”分隔的字符。 尝试使用 ifstream 逐行读取文件时,它无法读取文件,我在控制台上得到的输出为“无法打开输入文件。”。 我究竟做错了什么? 代码:-

void EnterFiles(string filename, int index)
{
    string line;
    vector<string> f1,f2;

    std::ifstream f;

    //prepare f to throw if failbit gets set

    std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
    f.exceptions(exceptionMask);
    try
    {
        f.open(filename);
    }
    catch (std::ios_base::failure& e)
    {
        std::cerr << e.what() << '\n';
    }
    if (!f)
    {
        cout << "Cannot open input file.\n";
    }
    while (getline(f,line) )
    {   
        if (index == 0)
        {
            f1.push_back(line);
            cout << line << endl;
        }
        else
        {
            f2.push_back(line);
            cout << line << endl;
        }
    }
    f.close();
}

【问题讨论】:

  • 使用文件的完整路径名。
  • 你没有给出你的文件路径,你的文件和你的程序在同一个目录吗?如果没有,你必须给它正确的路径。
  • 你应该尝试打印原因:stackoverflow.com/questions/17337602/…
  • 使用该路径,您需要从与文件相同的目录运行程序。你是如何运行你的程序的?
  • 包含exe的文件夹不一定是当前工作目录。

标签: c++ ifstream


【解决方案1】:

如果每次都满足条件,则跳过else部分。

提供完整或合格的文件路径(有时会产生问题!!), 另外,包括文件(如果不是!!)。

以下是与您的代码类似的示例,您可以参考, (经过我的检查,它在 Linux 中的作用就像一个魅力)

http://cpp-tutorial.cpp4u.com/STL_ifstream.html

希望,这个答案可能会有所帮助。

【讨论】:

  • 同时尝试以下操作:-
猜你喜欢
  • 1970-01-01
  • 2016-02-26
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
相关资源
最近更新 更多