句柄空字符串case从std :: istream提取一个字符串 [英] handle empty string case extracting a string from std::istream

查看:315
本文介绍了句柄空字符串case从std :: istream提取一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码从std :: istream中提取字符串:

Using the following code to extract a string from a std::istream :

#include <sstream>
#include <iostream>

void parse(std::istream & is, std::string & out)
{
    is >> out;
}

int main(int argc, char** argv)
{
    if (argc>1)
    {
        std::istringstream is(argv[1]);
        std::string out("__INIT__");
        std::cout << "good:"  << is.good() << " fail:"<< is.fail() <<  " eof:"<< is.eof()  << " in_avail:"<< is.rdbuf()->in_avail() << " value:" << out << std::endl;
        parse(is, out);
        std::cout << "good:"  << is.good() << " fail:"<< is.fail() <<  " eof:"<< is.eof()  << " in_avail:"<< is.rdbuf()->in_avail() << " value:" << out << std::endl;
    }
}

使用非空字符串时,输出如下所示:

With a non-empty string the output looks like :

$./a.out "TEST" 
good:1 fail:0 eof:0 in_avail:4 value:__INIT__
good:0 fail:0 eof:1 in_avail:0 value:TEST

输出如下:

$./a.out ""
good:1 fail:0 eof:0 in_avail:0 value:__INIT__
good:0 fail:1 eof:1 in_avail:0 value:__INIT__

而不是这样,我会期望:

Instead of this, I would expect :

good:1 fail:0 eof:0 in_avail:0 value:__INIT__
good:0 fail:0 eof:1 in_avail:0 value:

运算符>>不提取空字符串。

The operator>> does not extract an empty string. The result is the same with an empty string or and no data.

任何处理这种情况的建议都会感激。

Any suggestion to handle this situation will be appreciated.

推荐答案

如果您使用 parse 函数专用于提取,则可以简单地将其作为检查空缓冲区。如果有,清除字符串:

If you're using your parse function exclusively for extraction, you can simply make it out to be a check for an empty buffer. If there is, simply clear the string:

void parse(std::istream& is, std::string& out)
{
    if (is.eof() || is.peek() == std::char_traits<char>::eof())
    {
        out.clear();
        return;
    }

    is >> out;
}

这篇关于句柄空字符串case从std :: istream提取一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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