gpt4 book ai didi

c++ - 为什么 stringstream >> 在失败时更改目标值?

转载 作者:IT老高 更新时间:2023-10-28 13:58:58 25 4
gpt4 key购买 nike

来自 Stroustrup 的 TC++PL,第 3 版,第 21.3.3 节:

If we try to read into a variable v and the operation fails, the value of v should be unchanged (it is unchanged if v is one of the types handled by istream or ostream member functions).

下面的例子似乎与上面的引用相矛盾。根据上面的引用,我期望 v 的值保持不变——但它会归零。这种明显矛盾的行为有何解释?

#include <iostream>
#include <sstream>

int main( )
{
std::stringstream ss;

ss << "The quick brown fox.";

int v = 123;

std::cout << "Before: " << v << "\n";

if( ss >> v )
{
std::cout << "Strange -- was successful at reading a word into an int!\n";
}

std::cout << "After: " << v << "\n";

if( ss.rdstate() & std::stringstream::eofbit ) std::cout << "state: eofbit\n";
if( ss.rdstate() & std::stringstream::failbit ) std::cout << "state: failbit\n";
if( ss.rdstate() & std::stringstream::badbit ) std::cout << "state: badbit\n";

return 1;
}

我使用 x86_64-w64-mingw32-g++.exe (rubenvb-4.7.2-release) 4.7.2 得到的输出是:

Before: 123
After: 0
state: failbit

谢谢。

最佳答案

来自 this reference :

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set (until C++11)

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set. (since C++11)

您的编译器似乎在 C++11 模式下编译,这会改变行为。


输入运算符使用语言环境方面 std::num_getget 函数调用do_get .对于 C++11,它指定使用 std::strtoll等。人。函数类型。在 C++11 之前,它显然使用了 std::scanf样式解析(通过引用,我无权访问 C++03 规范)来提取数字。行为的变化是由于解析输入的变化造成的。

关于c++ - 为什么 stringstream >> 在失败时更改目标值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13378989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com