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?

c++

提问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

while (!infile.eof())does not work as you expected, eofsee one useful link

while (!infile.eof())没有按预期工作,eof查看一个有用的链接

Minor fix to your code, should work:

对您的代码进行小修,应该可以:

  ifstream infile("test.txt");

  if (infile.good())
  {
    string sLine;
    getline(infile, sLine);
    cout << sLine << endl;
  }

  infile.close();

回答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.

这应该逐行打印文件中的所有行。