繁体   English   中英

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

[英]Another istream discrepancy between libstdc++ and 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 ++标准描述了行为应该是什么?

ps我已经扩展了原来的测试程序,如下所示:

#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'

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

在这种情况下,你应该失败,但不是eof。 基本上,如果在失败之后,你可以清除错误并成功执行角色的get() ,那么你就不应该得到eof。 (如果你在clear()之后无法成功读取一个字符,你是否得到eof可能取决于你试图阅读的类型,也许在某些情况下,甚至可能取决于实现。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM