string转换为数值型,stoi( )的用法等
从string转换到数值型
stoi string to integer
将字符串转换为整数,解析str,将其内容解释为指定基的整数值,并将其作为int值返回。
若idx非空,函数将idx的值设置为str中数字后的第一个字符的位置。若该参数为空nullptr,则不使用。
base默认为10。base(进制)决定了哪些字符是有效,的以及它们的翻译。若base设为0,所使用的基数由序列中的格式决定。
//函数声明
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
//
size_t sz;
string a = " 101dsaada,ff";
string c = " 1010";
string d = "0xff";
cout << stoi(a, &sz) << endl; //101
cout << a[sz] << endl; //d &sz指向了d(第一个非数字字符)
cout << stoi(c) << endl; //1010
cout << stoi(c, nullptr, 8) << endl; //520
cout << stoi(c, nullptr, 0) << endl; //1010
cout << stoi(d) << endl; //0
cout << stoi(d, nullptr, 0) << endl; //255
cout << stoi(d, nullptr, 2) << endl; //0
string b = "s10";
string e = "100000000000000000000";
cout << stoi(b) << endl; //异常:字符串不合法
cout << stoi(e) << endl; //异常:转换后超出int范围
stol string to long
stoul string to unsigned long
stoll string to long long
stoull string to unsigned long long
以上和转换为int的情况类似,只是数字大小范围有变化。注意无符号数的合法范围为|0 ~ 2^n -1|,n是位数,在这个范围内的负数不会抛出异常,而是输出为:该负数加上模值2^n。
stod string to double
//函数声明
double stod (const string& str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);
//
size_t sz;
double e = 10.;
string a = " 10001.e";
string b = "12.5e2a5";
cout << stod(a, &sz) << endl; //10001
cout << a[sz] << endl; //e &sz指向e
cout << stod(b, &sz) << endl; //1250
cout << b[sz] << endl; //a &sz指向a
stof string to double
stold string to long double
和stod同理。