字符串数字变为(long long)int,float
1,利用atoi或者stoi进行转换
| atoi | 将char中存储的数字变为int类型,若string可以string.c_str()后再使用 | 越界会导致溢出 |
| stoi | 将string中存储的数字变为int类型 | 越界会导致运行错误 |
string s1="1654564564564512451",s2="000004546",s3="-4562415",s4; char ch[]="45645621",ch1[100]="15.4"; s4=ch1;//char*可以直接赋值给string cout<<stoi(s1);//超出int的范围,出现运行错误 cout<<stoll(s1)<<endl;//未超出long long cout<<atoi(s1.c_str())<<endl;//溢出 cout<<atoi(s2.c_str())<<endl;//正确 结果显示4546 cout<<atof(ch1)<<endl;//char->float cout<<s4; //s4="hello"+"world";错误 两个字符串字面值相加时+操作符的左右操作数必须至少有一个是string类
2,利用stream流进行转换,需要加上头文件<sstream>
1 #include <bits/stdc++.h> 2 using namespace std; 3 template<typename out_type,typename in_type> 4 out_type convert(const in_type &input) 5 { 6 stringstream stream; 7 stream<<input;//向流中传值 8 out_type result;//储存转换的结果 9 stream>>result;//向resul中写入值 10 return result; 11 } 12 int main() 13 { 14 float float_num =-99.876; 15 string double_str ="-87.89"; 16 int int_num = convert< int, char*>("-102");//将char类型数字-102转为int型 17 string float_str=convert<string,float>(float_num);//将float类型数字转为string型 18 double double_num=convert<double,string>(double_str);//将string类型数字转为double型 19 cout<<int_num<<endl<<double_num<<endl<<float_str; 20 return 0; 21 }
上述的模板函数只能将单个的in_put转换成out_put,可以做如下修改使得可将一串in_put转换成out_put,将其存储到vector中。
template<typename out_type,typename in_type> vector<out_type> convert(const in_type &input) { vector<out_type> v; stringstream stream; stream<<input;//向流中传值 out_type result;//储存转换的结果 while(stream>>result)//向result中写入值 { v.push_back(result);//将每个result存到动态数组中 } return v;返回值为vector }

浙公网安备 33010602011771号