我试图用之前回答的问题来解决这个问题,比如从字符串转换为浮点数会改变数字,但我没有成功。
在我的代码中,我采用一个充满“”字符的字符串,并使用 stringstream 将其转换为浮点数。它工作得很好(返回给我一个零值的浮点数),直到我在那之后立即执行了另一次转换。之后执行转换时,之前转换的 float 中存储的值不是零,而是 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 -Wall -Wextra -ansi -pedantic
任何形式的帮助将不胜感激,但我不愿意使用双打。