能實現字符串轉數字有三種方法,atof函數,sscanf函數和stringstream類。ios
具體demo代碼和運行結果c++
#include "stdio.h" #include <iostream> #include <> int main() { printf("字符串轉數字:stof()函數 string轉單精度浮點數\n"); std::string stof_str("686.123456789123456"); float stof_val = std::stof(stof_str); printf("stof_val=%.9f\n", stof_val); printf("字符串轉數字:stod()函數 string轉雙精度浮點數\n"); std::string stod_str("686.123456789123456"); double stod_val = std::stod(stod_str); printf("stod_val=%.9f\n", stod_val); printf("字符串轉數字:atof()函數\n"); char* atof_str = "123.123456789123456"; double atof_val = atof(atof_str); printf("atof_val=%.9f\n", atof_val); printf("字符串轉數字:sscanf()函數\n"); char* strInt = "123456789"; int strInt_num = 0; sscanf(strInt, "%d", &strInt_num); printf("strInt_num=%d\n", strInt_num); char* strLong = "1234567890123456789"; long long strLong_num = 0; sscanf(strLong, "%lld", &strLong_num); printf("strLong_num=%lld\n", strLong_num); char* strFloat = "1.23456789"; float strFloat_num = 0.0; sscanf(strFloat, "%f", &strFloat_num); printf("strFloat_num=%f\n", strFloat_num); char* strDouble = "1.23456789"; double strDouble_num = 0.0; sscanf(strDouble, "%lf", &strDouble_num); printf("strDouble_num=%.8lf\n", strDouble_num); printf("字符串轉數字:stringstream類\n"); stringstream ss; ss.clear(); printf("stringstream precision=%d\n", ss.precision()); string string_val1 = "1234567890"; int val1 = 0; ss.str(string_val1); ss >> val1; printf("val1=%d\n", val1); ss.clear(); string string_val2 = "1.234567890123456789"; double val2 = 0; ss.str(string_val2); ss >> val2; printf("val2=%.9f\n", val2); }
運行結果
字符串轉數字:stof()函數 string轉單精度浮點數
stof_val=686.123474121
字符串轉數字:stod()函數 string轉雙精度浮點數
stod_val=686.123456789
字符串轉數字:atof()函數
atof_val=123.123456789
字符串轉數字:sscanf()函數
strInt_num=123456789
strLong_num=1234567890123456789
strFloat_num=1.234568
strDouble_num=1.23456789
字符串轉數字:stringstream類
stringstream precision=6
val1=1234567890
val2=1.234567890函數