C++ 如何从文件中读取第一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14867944/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:45:40 来源:igfitidea点击:
How can i read first line from file?
提问by user2036891
ifstream infile;
string read_file_name("test.txt");
infile.open(read_file_name);
string sLine;
while (!infile.eof())
{
getline(infile, sLine);
cout << sLine.data() << endl;
}
infile.close();
This program prints all line in the file, but I want to print only first line.
该程序打印文件中的所有行,但我只想打印第一行。
回答by billz
回答by Dkrtemp
You can try this:
你可以试试这个:
ifstream infile;
string read_file_name("test.txt");
infile.open(read_file_name);
string sLine;
while (!infile.eof())
{
infile >> sLine;
cout << sLine.data() << endl;
}
infile.close();
This should print all the lines in your file, line by line.
这应该逐行打印文件中的所有行。