如何在 C++ 中打开 .txt 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16991601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I open a .txt file in C++?
提问by user2464737
#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;
}
Why does this not print out what is in my "hey.txt" file?
为什么这不打印出我的“hey.txt”文件中的内容?
回答by varun
This should do the job, If you are new to these things please read http://www.cplusplus.com/doc/tutorial/files/
这应该可以完成工作,如果您不熟悉这些东西,请阅读http://www.cplusplus.com/doc/tutorial/files/
EDIT: in article above .good() is a bad practice, look here if you need to more detail Testing stream.good() or !stream.eof() reads last line twice
编辑:在上面的文章中 .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;
}