1

std::istream::getline()入力バッファを最大化するのではなく、それが区切り文字に到達したことを確認するにはどうすればよいですか?

gcount()バッファが保持しているバイトよりも少ないバイトが読み取られたかどうかを判断するために使用できることに気付きましたが、読み取る行がバッファとまったく同じ長さである場合はどうなりますか?到達\nすることは、到達しないこととまったく同じように見えます\n

4

2 に答える 2

4

Don't use member getline at all. The following will always work, using the free function:

#include <string>

std::string line;

if (!std::getline(infile, line)) { /* error */ }

// entire line in "line"

(The answer to your actual question is that you must use member-getline in a loop. But why bother.)

于 2012-10-11T14:30:50.457 に答える
0

The conditions for terminating std::istream::getline() are quite precise: If the function stops because n - 1 were stored but no newline was reached, the flag std::ios_base::failbit is set. That is, you can just check the state of the stream to determine if a newline was reached.

That said, unless you need to protect against hostile sources of your data (e.g. an Internet connection send you data until you run out of memory, all on just one line), you should use the std::string version:

std::string line;
std::getline(in, line);
于 2012-10-11T16:13:48.350 に答える