书上一道题,用未格式化版本的getline逐行读取一个文件,再将读到的内容打出来,我是这样编写的:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream input("C:/Users/0e/Desktop/1.txt");
char s[5];
while (!input.eof())
{
input.getline(s, 5, '\n');
cout<<s;
}
}
先不说别的问题,就说我的本意是用字符数组连续读写内容,为什么这个程序只能打出5个字符?
PHPz2017-04-17 13:16:23
When
calls input.getline(s, 5, 'n');
, you will get four possible flow states, leaving aside the most serious but least common badbit
. There are three remaining possibilities:
There are less than 5 characters in the file, and the status is set to eofbit. The program outputs these characters and ends normally.
There are more than 5 characters in the file, but there is no specified delimiter 'n' in the first 5 characters. The status is set to failbit. After the characters that have been read in the output stream, an exception is thrown. But because The status is not eofbit, so there is an infinite loop, exceptions are constantly thrown, and there are no characters read into the stream, so the phenomenon you mentioned is caused.
There are more than 5 characters in the file, and the first 5 characters contain the specified delimiter 'n', the status is set to goodbit, the characters in the output stream are output, and the next loop is continued until 1 or 2 is encountered. situation.
That’s why.
Let’s talk about how to use getline in this case.
Because I don’t know what your 1.txt is, changing it to stringstream
is the same. Modify your program as follows:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
istringstream input("das\ndsa\nddas\ndass\nad\nsadasd");
char s[5];
while (input.getline(s, 5, '\n'))
{
cout << s << endl;
cout << "(" << input.rdstate() << ")" << endl; // debug: goodbit
}
cout << "(" << input.rdstate() << ")" << endl; // debug: failbit
}
To illustrate the reason, I output the current flow status in parentheses to help you understand.
天蓬老师2017-04-17 13:16:23
std::string line;
std::getline(file, line, '\n');
http://en.cppreference.com/w/cpp/string/basic_string/getline