gpt4 book ai didi

c++ - 我如何从文件中读取第一行?

转载 作者:可可西里 更新时间:2023-11-01 17:35:30 24 4
gpt4 key购买 nike

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();

这个程序打印文件中的所有行,但我只想打印第一行。

最佳答案

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

对您的代码进行较小的修复,应该可以工作:

  ifstream infile("test.txt");

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

关于c++ - 我如何从文件中读取第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com