【问题标题】:Why won't my cout statements print after opening a textfile?为什么打开文本文件后我的 cout 语句不打印?
【发布时间】:2017-01-08 19:50:14
【问题描述】:

我正在尝试编写一个程序,在其中读取文本文件,然后将文本文件中的每一行存储在字符串向量中。我想我可以打开文本文件,但是我注意到在我打开文本文件之后,在那之后的任何内容都不会执行。例如,我的 main 函数末尾有一个 cout 语句,当我输入不存在的文件名时会输出。但是,如果我输入的文件名确实存在,我不会从最后一个 cout 语句中得到任何输出。有谁知道这是为什么?谢谢!

int main() { vector<string>line; string fileName = "test.txt"; ifstream myFile(fileName.c_str()); int i = 0; int count = 0; vector<string>lines; cout << "test" << endl; if (myFile.is_open()) { cout << "test2" << endl; while (!myFile.eof()) { getline(myFile, lines[i],'\n'); i++; } myFile.close(); } if (!myFile.is_open()) { cout<< "File not open"<< endl; } myFile.close(); cout << "Test3" <<endl; return 0; }

【问题讨论】:

  • lines 是一个空向量。 lines[i] 对于i 的任何值都无效。你的程序就崩溃了。
  • 你用lines[i]写出向量的边界
  • 使用std::string逐行获取并将其推入向量中。
  • 考虑通过调试器运行您的代码。调试器会显示 getline() 非常快地抛出异常。

标签: c++ ifstream cout


【解决方案1】:

试试this:

string fileName = "test.txt";
ifstream myFile(fileName); // .c_str() not needed - ifstream can take an actual string
vector<string> lines;

string line; // temporary variable for std::getline
while (getline(myFile, line)) {
   lines.push_back(line); // use push_back to add new elements to the vector
}

正如 cmets 中所指出的,您的程序似乎过早“结束”的最可能原因是它正在崩溃。 std::getline 将引用-string 作为其第二个参数。在您的代码中,您的向量是空的;因此,任何ilines[i] 返回对无效内存的引用。当getline 尝试访问该内存时,程序会崩溃。

如果您希望在尝试访问 vector 的越界索引时引发异常,请使用 lines.at(i) 而不是 lines[i]

【讨论】:

    【解决方案2】:

    你需要使用push_back(),因为你的初始向量是空的,你不能在空向量上使用索引。如果这样做,将导致未定义的行为。

    std::ifstream input( "filename.ext" );
    std::vector<std::string> lines;
    for( std::string line; getline( input, line ); )
    {
        lines.push_back(line); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 2023-04-09
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      相关资源
      最近更新 更多