c/c++再学习:常用字符串转数字操作
c/c++再学习:常用字符串转数字操作
能实现字符串转数字有三种方法,atof函数,sscanf函数和stringstream类。
具体demo代码和运行结果
#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