为什么std :: operator>>(istream& char; amp;)提取空格? [英] Why does std::operator>>(istream&, char&) extract whitespace?

查看:201
本文介绍了为什么std :: operator>>(istream& char; amp;)提取空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编译以下程序,并且我了解到, char& 的提取器继续提取一个字符,即使它是一个空格字符。我禁用了跳过前导空格字符,希望继续读取尝试失败(因为格式化提取停止在空格),但是成功时感到惊讶。

  #include< iostream> 
#include< sstream>

int main()
{
std :: istringstream iss(a b c);
char a,b,c;

iss>> std :: noskipws;

if(iss>> a>> b>> c)
{
std :: cout< a = \ \\ nc = \<< c<<'\\\
';
}
}


输出:

  a =a
b =
c =b


从输出中可以看出, b 给出了ab; c 给出以下字符b b c 没有一个值,因为提取应该失败,因为

解决方案

在IOStreams中,字符几乎没有格式要求任何和所有字符在字符序列中是用于提取的有效候选。对于使用数字面的提取器,提取被定义为在空白处停止。然而, charT& 的提取器直接在缓冲区上工作,不加选择地返回下一个可用字符,大概是通过调用 rdbuf() - > sbumpc ()



不要假定这种行为扩展到指向字符的指针的提取器,因为它们的提取被明确定义为停止在空格。


I was compiling the following program and I learned that the extractor for a char& proceeds to extract a character even if it is a whitespace character. I disabled the skipping of leading whitespace characters expecting the proceeding read attempts to fail (because formatted extraction stops at whitespace), but was surprised when it succeeded.

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream iss("a b c");
    char a, b, c;

    iss >> std::noskipws;

    if (iss >> a >> b >> c)
    { 
        std::cout <<     "a = \"" << a
                  << "\"\nb = \"" << b
                  << "\"\nc = \"" << c << '\n';
    }
}

Output:

a = "a"
b = " "
c = "b"

As you can see from the output, b was given the value of the space between "a" and "b"; and c was given the following character "b". I was expecting both b and c to not have a value at all since the extraction should fail because of the leading whitespace. What is the reason for this behavior?

解决方案

In IOStreams, characters have virtually no formatting requirements. Any and all characters in the character sequence are valid candidates for an extraction. For the extractors that use the numeric facets, extraction is defined to stop at whitespace. However, the extractor for charT& works directly on the buffer, indiscriminately returning the next available character presumably by a call to rdbuf()->sbumpc().

Do not assume that this behavior extends to the extractor for pointers to characters as for them extraction is explicitly defined to stop at whitespace.

这篇关于为什么std :: operator&gt;&gt;(istream&amp; char; amp;)提取空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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