将字符串转换为C ++中的float [英] converting string to float in c++
问题描述
鉴于字符串可能无效,将字符串转换为float的最佳方法是什么(在c ++中). 这是输入的类型
What is the best way to convert a string to float(in c++), given that the string may be invalid. Here are the type of input
20.1
0.07
x
0
我使用了 strtof ,效果很好,但问题是它在错误以及将字符串"0"传递给函数时都返回0.
I used strtof which works quite well but the issue is it returns 0 both on error as well as when string "0" is passed into the function.
我使用的代码非常简单
float converted_value = strtof(str_val.c_str(), NULL);
if (converted_value == 0) {
return error;
}
有什么办法可以修复此代码,以便区分字符串0和错误0? 如果我使用scanf有什么缺点?
Is there any way I could fix this code so I can differentiate between string 0 and error 0? what are the disadvantages if I use scanf?
推荐答案
您可以通过不忽略第二个参数来做到这一点-它会告诉您扫描在哪里停止.如果它是字符串的结尾,那么就没有错误.
You do it by not ignoring the second parameter - it will tell you where the scanning stopped. If it's the end of the string then there wasn't an error.
char *ending;
float converted_value = strtof(str_val.c_str(), &ending);
if (*ending != 0) // error
这篇关于将字符串转换为C ++中的float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!