使用字符串流从空字符串转换为浮点值会导致非零值

conversion from empty string to float using stringstream results in non-zero value

本文关键字:字符串 非零值 转换      更新时间:2023-10-16

我曾试图用之前回答的问题来解决这个问题,比如从字符串到浮点的转换会改变数字,但我没有成功。

在我的代码中,我获取一个充满"字符的字符串,并使用字符串流将其转换为浮点值。它工作得很好(给我返回了一个零值浮点值),直到我执行了另一个转换。当随后执行转换时,先前转换的浮点中存储的值不是零,而是4.57048e-41。我希望下面的代码能更清楚地解释我的问题。

我从开始

std::stringstream ss;
float a;
float b;
for(int i=0; i<LIM; ++i){
    //some other conversions using same stringstream
    //clearing stringstream    
    ss.str( std::string() );
    ss.clear();
    ss << str1;    //string full of empty spaces, length of 5
    ss >> a;
    std::cout << a;//prints zero
}

这很好,但当我把它改成时

std::stringstream ss;
float a;
float b;
for(int i=0; i<LIM; ++i){
    //some other conversions using same stringstream
    //clearing stringstream    
    ss.str( std::string() );
    ss.clear();
    ss << str1;    //string full of empty spaces, length of 5
    ss >> a;
    std::cout << a;//prints 4.57048e-41
    ss.str ( std::string() );
    ss.clear();
    ss << str2;    //another string full of empty spaces, length of 5
    ss >> b;
    std::cout << b;//prints zero
}

我使用的gcc 4.6.3带有以下标志:-o2-墙-Wextra-ansi-迂腐

任何形式的帮助都将不胜感激,但我不愿意使用替身。

非常感谢

如果转换失败,则不会更改目标值。在您的情况下,它仍然具有其原始的未初始化的值;因此打印它会产生垃圾或其他未定义的行为。

您应该检查转换是否成功:

if (!(ss >> a)) {
    a = 0; // or handle the failure
}

或者使用像C++11中的std::stofboost::lexical_cast这样的转换函数,它们抛出表示转换失败。(或者,正如评论中所提到的,如果您不需要检测故障,只需将其设置为零即可)。