C ++:getline()读取了整行吗? [英] C++: Did getline() read entire line?

查看:386
本文介绍了C ++:getline()读取了整行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证 std :: istream :: getline()是否已达到分隔符,而不是仅仅最大化输入缓冲区?

How can I verify that std::istream::getline() reached the delimiter, instead of just max-ing out the input buffer?

我意识到我可以使用 gcount()来确定是否读取了比缓冲区保持更少的字节,但是读取与缓冲区完全一样长?到达 \ n 看起来与未到达 \ n 完全相同。

I realize that I can use gcount() to determine whether fewer bytes than the buffer holds were read, but what if the line to read is exactly as long as the buffer? Reaching \n would look exactly the same as not reaching \n.

推荐答案

终止 std :: istream :: getline()的条件非常精确:如果函数因为 n - 1 已存储但没有到达换行符,因此设置了标志 std :: ios_base :: failbit 。也就是说,您只需检查流的状态以确定是否已达到换行符。

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.

这就是说,除非您需要保护您的数据的恶意来源(例如,一个互联网连接发送数据,直到你的内存不足,所有只在一行),你应该使用 std :: string 版本:

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

这篇关于C ++:getline()读取了整行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆