【问题标题】:istream get method behavioristream 获取方法行为
【发布时间】:2009-11-05 14:41:14
【问题描述】:

我读了istream::get,但仍有疑问。假设我的分隔符实际上是 NULL '\0' 字符,在这种情况下会发生什么?从我读到的:

If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. Use getline if you want this character to be extracted (and discarded). The ending null character that signals the end of a c-string is automatically appended at the end of the content stored in s.

我更喜欢“get”而不是“readline”的原因是能够将字符流提取到“streambuf”中。

【问题讨论】:

    标签: c++ istream


    【解决方案1】:

    我不太明白你的问题。

    在 msdn 网站上,对于 get 函数,它说:

    在所有情况下,分隔符既不会从流中提取,也不会由函数返回。相比之下,getline 函数提取但不存储分隔符。 在所有情况下,分隔符既不是从流中提取的,也不是由函数返回的。相比之下,getline 函数提取但不存储分隔符。

    http://msdn.microsoft.com/en-us/library/aa277360(VS.60).aspx

    我认为您不会有问题,因为 msdn 网站告诉您,分隔符既不是从流中提取的,也不是通过函数返回的。

    或者我在这里遗漏了一点?

    【讨论】:

    • 那么处理分隔符卡在输入流中的常用方法是什么? (你能告诉我我是 C++ 流的菜鸟吗 ;-)
    • .ignore(1) 似乎合适。
    【解决方案2】:

    如果你有这样的东西,那么分隔符就不会卡在输入流中:

    std::string read_str(std::istream & in)
    {
            const int size  = 1024;
            char pBuffer[size];
            in.getline(pBuffer, size, '\0');
            return std::string(pBuffer);
    }
    

    如果您使用 '\0' 作为分隔符并且字符串不大于 1024 字节,这只是一个示例。

    【讨论】:

    • 感谢 AlexKR。我正在寻找一种基于将输入字符流传输到streambuf 的解决方案,如果我理解正确,它会负责自动调整大小活动。
    猜你喜欢
    • 2014-05-23
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2011-02-23
    • 2014-04-11
    • 2011-06-21
    相关资源
    最近更新 更多