简体   繁体   English

在c ++中将字符串转换为float

[英]converting string to float in c++

What is the best way to convert a string to float(in c++), given that the string may be invalid. 将字符串转换为float(在c ++中)的最佳方法是什么,因为字符串可能无效。 Here are the type of input 这是输入的类型

20.1 20.1

0.07 0.07

x X

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. 我使用strtof工作得很好,但问题是它在错误时以及字符串“0”传递给函数时返回0。

The code I am using is pretty simple 我使用的代码非常简单

float converted_value = strtof(str_val.c_str(), NULL);
if (converted_value == 0) {
    return error;
}

Is there any way I could fix this code so I can differentiate between string 0 and error 0? 有什么方法可以修复此代码,以便区分字符串0和错误0吗? what are the disadvantages if I use scanf? 如果我使用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++11 actually has functions that do this now, in your case std::stof C ++ 11实际上具有现在执行此操作的函数,在您的情况下为std::stof

Note that as far as handling your validation, it will throw an std::invalid_argument exception if the argument cannot be converted. 请注意,就处理验证而言,如果无法转换参数,它将抛出std::invalid_argument异常。

For completeness, here are more of such functions 为了完整起见,这里有更多这样的功能

std::stoi    // string to int
std::stol    // string to long
std::stoll   // string to long long
std::stof    // string to float
std::stod    // string to double
std::stold   // string to long double

Do neither and use stringstream . 不要使用stringstream

std::stringstream s(str_val);

float f;
if (s >> f) {
    // conversion ok
} else {
    // conversion not ok
}

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

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