[英]C++: Using ifstream with getline();
Check this program检查这个程序
ifstream filein("Hey.txt");
filein.getline(line,99);
cout<<line<<endl;
filein.getline(line,99);
cout<<line<<endl;
filein.close();
The file Hey.txt has alot of characters in it. Hey.txt 文件中有很多字符。 Well over a 1000
超过1000
But my question is Why in the second time i try to print line.但我的问题是为什么我第二次尝试打印行。 It doesnt get print?
它没有得到打印?
The idiomatic way to read lines from a stream is this:从流中读取行的惯用方法是:
std::ifstream filein("Hey.txt");
for (std::string line; std::getline(filein, line); )
{
std::cout << line << std::endl;
}
Notes:笔记:
No close()
.没有
close()
。 C++ takes care of resource management for you when used idiomatically. C++ 在习惯使用时会为您处理资源管理。
Use the free std::getline
, not the stream member function.使用免费的
std::getline
,而不是流成员函数。
#include<iostream>
using namespace std;
int main()
{
ifstream in;
string lastLine1;
string lastLine2;
in.open("input.txt");
while(in.good()){
getline(in,lastLine1);
getline(in,lastLine2);
}
in.close();
if(lastLine2=="")
cout<<lastLine1<<endl;
else
cout<<lastLine2<<endl;
return 0;
}
正如 Kerrek SB 所说,有两种可能性:1)第二行是空行 2)没有第二行,所有超过 1000 个字符都在一行中,所以第二个getline
没有什么可获取的。
An easier way to get a line is to use the extractor operator of ifstream
获取一行的更简单方法是使用
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;
}
One problem here though is that it won't work when the line have a space ' '
because it is considered a field delimiter in ifstream
.但这里的一个问题是,当该行有一个空格
' '
时它不会工作,因为它被认为是ifstream
中的字段定界符。 If you want to implement this kind of solution change your field delimiter to eg -
/
or any other field delimiter you like.如果您想实施这种解决方案,请将您的字段分隔符更改为例如
-
/
或您喜欢的任何其他字段分隔符。
If you know how many spaces there is you can eat all the spaces by using other variables in the extractor operator of ifstream.如果您知道有多少空格,您可以通过在 ifstream 的提取器运算符中使用其他变量来吃掉所有空格。 Consider the file has contents of first name last name.
考虑文件的内容是名字姓氏。
//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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.