一、string转int
1. 使用string流
/* 字符串转整型 */
/*
* istringstream:从 string 读取数据
* ostringstream:向 string 写入数据
* stringstream:既可从 string 读数据,也可向 string 写数据
*/
void StrToInt(const string &s)
{
int num = 0;
stringstream ss;
ss << s;
ss >> num;
cout << num << endl;
}
2. 采用标准库中 atoi 函数
/* 字符串转整型 */
void StrToInt(const string &s)
{
int num = 0;
// 将string类型先转化为const char*类型
const char *str = s.c_str();
num = atoi(str);
cout << num << endl;
}
3. 采用 stoi 函数
/* 字符串转整型 */
/*
* 注:某些老版本的string不支持该函数
* 原型:int stoi (const string &str, size_t *idx = 0, int base = 10);
*/
void StrToInt(const string &s)
{
int num = 0;
num = stoi(s); // 等价于stoi(s, 0, 10);
cout << num << endl;
}
二、int转string
1. 使用string流
/* 整型转字符串 */
void IntToStr(int i)
{
string s;
stringstream ss;
ss << i;
ss >> s;
cout << s << endl;
}
2. 使用 sprintf 函数
/* 整型转字符串 */
/*
* 原型:int sprintf (char *buffer, const char *format, [argument]...);
*/
void IntToStr(int i)
{
string s;
char *str;
sprintf(str, "%d", i);
s = str;
cout << s << endl;
}
3. 使用 to_string 函数
/* 整型转字符串 */
/*
* 原型:string to_string (int val);
*/
void IntToStr(int i)
{
string s;
s = to_string(i);
cout << s << endl;
}