如何在 C++ 中打开 .txt 文件?

use*_*737 -1 c++ fstream file ifstream

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile("hey.txt");

  myfile >> line;
  cout << line;
  system("pause");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么这不打印出我的“hey.txt”文件中的内容?

var*_*run 7

这应该可以完成工作,如果您对这些东西不熟悉,请阅读http://www.cplusplus.com/doc/tutorial/files/

编辑:在上面的文章中 .good() 是一种不好的做法,如果您需要更多详细信息,请查看此处测试stream.good() 或 !stream.eof() 读取最后一行两次

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {

    while(getline(myfile, line)) {
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 您复制并粘贴了一些错误的示例代码。`while (myfile.good())` 循环是一种[不好的做法](http://stackoverflow.com/questions/4324441/testing-stream-good-or-stream-eof-reads-last-line-twice )。 (2认同)