检查这个程序
ifstream filein("Hey.txt");
filein.getline(line,99);
cout<<line<<endl;
filein.getline(line,99);
cout<<line<<endl;
filein.close();
文件 Hey.txt 中有很多字符。远超1000
但我的问题是为什么我第二次尝试打印行。它没有得到打印?
原文由 Mohamed Ahmed Nabil 发布,翻译遵循 CC BY-SA 4.0 许可协议
检查这个程序
ifstream filein("Hey.txt");
filein.getline(line,99);
cout<<line<<endl;
filein.getline(line,99);
cout<<line<<endl;
filein.close();
文件 Hey.txt 中有很多字符。远超1000
但我的问题是为什么我第二次尝试打印行。它没有得到打印?
原文由 Mohamed Ahmed Nabil 发布,翻译遵循 CC BY-SA 4.0 许可协议
获得一条线的更简单方法是使用提取器运算符 ifstream
string result;
//line counter
int line=1;
ifstream filein("Hey.txt");
while(filein >> result)
{
//display the line number and the result string of reading the line
cout << line << result << endl;
++line;
}
但是这里的一个问题是,当该行有空格时它不起作用 ' '
因为它被认为是 ifstream
中的字段分隔符。如果您想实施这种解决方案,请将您的字段分隔符更改为例如 -
/
或您喜欢的任何其他字段分隔符。
如果您知道有多少个空格,您可以通过使用 ifstream 的提取器运算符中的其他变量来吃掉所有的空格。考虑该文件具有名字姓氏的内容。
//file content is: FirstName LastName
int line=1;
ifstream filein("Hey.txt");
string firstName;
string lastName;
while(filein>>firstName>>lastName)
{
cout << line << firstName << lastName << endl;
}
原文由 0xDEADBEEF 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
根据 C++ 参考( 此处)getline 设置
ios::fail
时提取了 count-1 个字符。您必须在getline()
调用之间调用filein.clear();
。