c++ - 如何判断 `std::getline()`提取了多少个字符?

标签 c++ iostream

假设我通过使用 std::getline()std::istream 中读取了一个 std::string重载。如何确定从流中提取了多少个字符? std::istream::gcount()不像这里讨论的那样工作:ifstream gcount returns 0 on getline string overload

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::istringstream s( "hello world\n" );
    std::string str;
    std::getline( s, str );
    std::cout << "extracted " << s.gcount() << " characters" << std::endl;
}

Live example

请注意,对于反对者 - 字符串的长度不是答案,因为 std::getline() 可能会也可能不会从流中提取额外的字符。

最佳答案

这样做似乎并不完全简单,因为 std::getline 可能(或可能不会)读取终止定界符,并且在任何一种情况下都不会将其放入字符串中。所以字符串的长度不足以告诉你到底读取了多少个字符。

您可以测试 eof() 以查看分隔符是否被读取:

std::getline(is, line);

auto n = line.size() + !is.eof();

最好将它包装在一个函数中,但是如何传回额外的信息呢?

我想的一种方法是在读取定界符后将其添加回去,并让调用者处理它:

std::istream& getline(std::istream& is, std::string& line, char delim = '\n')
{
    if(std::getline(is, line, delim) && !is.eof())
        line.push_back(delim); // add the delimiter if it was in the stream

    return is;
}

但我不确定我会一直想要那个。

关于c++ - 如何判断 `std::getline()`提取了多少个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53685373/

相关文章:

Java 流操作

c++ - 运算符重载决议如何在 namespace 内工作?

c++ - 在清除 istream 之前我不需要取消它吗?

c++ - C++中二进制和txt模式有什么区别

c++ - std::iostream 读取或写入计数为零且缓冲区无效

c++ - iostream 迭代器如何工作?

c++将文本文件读入整数和字符串

c++ - 将函数指针传递给函数,c++

c++ - 构造函数和继承?

c++ - std::bind 与 std::less_equal