libstdc ++和libc ++之间的另一个奇怪的差异

时间:2014-03-06 19:16:47

标签: c++ stringstream istream libstdc++ libc++

这个简单的代码:

#include <iostream>
#include <sstream>
int main()
{
   float x = 0.0;
   std::stringstream ss("NA");
   ss >> x;

    std::cout << ( ss.eof() ? "is" : "is not") << " at eof; x is " << x << std::endl;
}

返回不同的结果,具体取决于我选择的库(我在OSX 10.9上从xcode 5运行clang):

clang++ -std=c++11 -stdlib=libstdc++ -> not at eof
clang++ -stdlib=libstdc++ -> not at eof
/usr/bin/g++-4.2 -> not at eof

clang++ -std=c++11 -stdlib=libc++ -> at eof
clang++ -stdlib=libc+ -> at eof

在我看来,如果我尝试将字母字符读入浮点数,操作应该失败,但它不应该吃无效字符 - 所以我应该失败()而不是eof(),所以这看起来像是libc ++中的一个错误。

是否有某个c ++标准描述了行为应该是什么?

P.S。我已经扩展了原来的测试程序:

#include <iostream>
#include <sstream>
int main()
{
   float x = 0.0;
   std::stringstream ss("NA");
   ss >> x;
    std::cout << "stream " << ( ss.eof() ? "is" : "is not") << " at eof and " << (ss.fail() ? "is" : "is not") << " in fail; x is " << x << std::endl;
    if (ss.fail())
    {
        std::cout << "Clearing fail flag" << std::endl;
        ss.clear();
    }
   char c = 'X';
    ss >> c;
    std::cout << "Read character: \'" << c << "\'" << std::endl;
}

这就是我所看到的:

使用libc ++:

stream is at eof and is in fail; x is 0
Clearing fail flag
Read character: 'X'

使用stdlibc ++:

stream is not at eof and is in fail; x is 0
Clearing fail flag
Read character: 'N'

p.p.s。如在n.m.的问题中所述。链接到,如果stringstream设置为“MA”而不是“NA”,则不会出现问题。显然,libc ++开始解析字符串,认为它会变为“NAN”,然后当它没有时,它会变得很烦恼。

1 个答案:

答案 0 :(得分:2)

在这种情况下,你应该失败,但不是eof。基本上,如果, 失败后,您可以清除错误并成功完成 一个get()的角色,你不应该得到eof。 (如果你 是否无法在clear()之后成功读取字符 你得到或不依赖于你想要的类型 阅读,也许在某些情况下,甚至是实施。)