-2
#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;
}

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

4

1 回答 1

4

这应该可以完成工作,如果您对这些东西不熟悉,请阅读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;
}
于 2013-06-07T19:33:18.857 回答