使用字符串流从空字符串转换为浮点值会导致非零值
conversion from empty string to float using stringstream results in non-zero value
我曾试图用之前回答的问题来解决这个问题,比如从字符串到浮点的转换会改变数字,但我没有成功。
在我的代码中,我获取一个充满"字符的字符串,并使用字符串流将其转换为浮点值。它工作得很好(给我返回了一个零值浮点值),直到我执行了另一个转换。当随后执行转换时,先前转换的浮点中存储的值不是零,而是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::stof
或boost::lexical_cast
这样的转换函数,它们抛出表示转换失败。(或者,正如评论中所提到的,如果您不需要检测故障,只需将其设置为零即可)。
相关文章:
- 在索引0为0的数组中查找非零最小值C++
- 用非零值初始化void指针的正确(或最安全)方法
- 获取 2 暗淡 cv::Mat 的非零元素的值
- MEMCMP以相同(零值)位字段结构返回非零
- 特征稀疏布尔矩阵是否存储非零值
- pthreads_create()返回非零值
- 任务 ":app:ndkBuild" 执行失败。>进程'Command'完成,退出值为非零 2
- C 排序升序非零值
- MySQL 使用一组列中的数据更新列,以非零值为准
- 如何在编译时将整数模板参数修改为非零值
- 如何获取非零矩阵的值
- 比较/计数非零返回比预期更大的值
- 使用字符串流从空字符串转换为浮点值会导致非零值
- 编译器是否应该正确地将布尔中的任意非零值解释为true
- 如何在 c++ 中获取向量中第一个非零值的索引<int>
- C++数值类型的非零默认值 - 重塑
- 将双数组初始化为非零值
- 确定非零最小值的最快方法
- 如何保护数组定义,防止使用非零值进行不完整的初始化
- 如何强制编译器为未初始化的变量设置非零值