簡體   English   中英

在c ++中將字符串轉換為float

[英]converting string to float in c++

將字符串轉換為float(在c ++中)的最佳方法是什么,因為字符串可能無效。 這是輸入的類型

20.1

0.07

X

0

我使用strtof工作得很好,但問題是它在錯誤時以及字符串“0”傳遞給函數時返回0。

我使用的代碼非常簡單

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

有什么方法可以修復此代碼,以便區分字符串0和錯誤0嗎? 如果我使用scanf有什么缺點?

你不要忽略第二個參數,它會告訴你掃描停止的位置。 如果它是字符串的結尾,則沒有錯誤。

char *ending;
float converted_value = strtof(str_val.c_str(), &ending);
if (*ending != 0) // error

C ++ 11實際上具有現在執行此操作的函數,在您的情況下為std::stof

請注意,就處理驗證而言,如果無法轉換參數,它將拋出std::invalid_argument異常。

為了完整起見,這里有更多這樣的功能

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

不要使用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