一、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;
}
