【发布时间】:2010-09-21 22:36:58
【问题描述】:
我正在尝试找到一种方法来从文件中读取某些内容,将其放入字符串中,然后将其输出到屏幕上。如果你知道怎么做,你能举个例子吗?
【问题讨论】:
我正在尝试找到一种方法来从文件中读取某些内容,将其放入字符串中,然后将其输出到屏幕上。如果你知道怎么做,你能举个例子吗?
【问题讨论】:
ifstream infile("myfile.txt");
std::string line;
// Reads the first line from the file and stores it into 'line'
std::getline(infile, line);
infile.close();
std::cout << line;
此代码将读取文件的整个第一行。 如果你想逐行读取文件,你可以这样做:
while (!infile.eof) {
std::getline(infile, line);
std::cout << line << "\n"; // Not sure if std::getline includes the line terminator
}
不确定“需要阅读一些东西”是什么意思,但您可以使用字符串流进行转换。
【讨论】:
ifstream fin ("input.txt");
char line [200];
streamsize size (200);
fin.getline(line, size);
//or you could do:
// string str; fin >> str;
//for every space sepped string in the file
cout << line << endl;
【讨论】:
std::string更安全。