C++中 int 与 string 的转换
1. int 转为 string
1.1 to_string
c++11标准增加了全局函数to\_string。
int main()
{
string str = "April's age is: " + to_string(18);
cout << str << endl;
return 0;
}
输出结果:
April's age is: 18
1.2 ostringstream
采用字符串流对象来实现。
int main()
{
int age = 18;
ostringstream os; //构造字符串流
os << age; //向字符串流中写入内容
cout << os.str() << endl; //输出字符串流中的内容
return 0;
}
2.string 转为 int
2.1 stoi
int main()
{
string str_dec = "18";
string str_hex = "40c3";
string str_bin = "10010110001";
string str_auto = "0x7f";
cout << str_dec << ": " << stoi(str_dec) << endl;
cout << str_hex << ": " << stoi(str_hex, nullptr, 16) << endl;
cout << str_bin << ": " << stoi(str_bin, nullptr, 2) << endl;
cout << str_auto << ": " << stoi(str_auto, nullptr, 0) << endl;
return 0;
}
输出结果:
18: 18
40c3: 16579
10010110001: 1201
0x7f: 127
2.2 istringstream
int main()
{
istringstream is("18"); //构造输入字符串流
int age ;
is >> age;
cout << age << endl;
return 0;
}
输出结果
18
还没有评论,来说两句吧...