问题描述
我正在编译以下程序,并且我了解到, 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<<'\\\
';
}
}
从输出中可以看出,
b
给出了a
和b
;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'; } }
As you can see from the output,
b
was given the value of the space between"a"
and"b"
; andc
was given the following character"b"
. I was expecting bothb
andc
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 tordbuf()->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>>(istream& char; amp;)提取空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!