代码之家  ›  专栏  ›  技术社区  ›  Slava

如何确定提取了多少个字符`std::getline()`?

  •  3
  • Slava  · 技术社区  · 7 年前

    假设我读了一本书 std::string 从…起 std::istream std::getline() 超载。如何确定从流中提取的字符数? 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

    注意,对于下拉列表,字符串的长度不是答案,如下所示 可以或不可以从流中提取其他字符。

    1 回复  |  直到 7 年前
        1
  •  6
  •   Galik    7 年前

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