c++字符串与整形相互转换的方法
-
字符串转整形
-
stoi //越界会报错
int stoi (const string& str, size_t* idx = 0, int base = 10);
-
stringstream ss
-
atoi 在特定场景下使用
-
-
-
整形转换为字符串
-
to_string
-
stringstream ss
-
sprintf
-
itoa //可以转换为任意进制
-
解决输入的问题
scanf和cin不能输入带空格的字符串
getline和gets可以解决带空格字符串的输入
如果getline前面有输入,getline会吞掉上次输入的回车换行
使用getchar吞掉上次输入的回车换行,getline就可以正常输入了
解决任意进制转换的问题
2-36(radix)进制转换为10进制数
int toDecimal(string s, int radix)
{
int total = 0;
for (auto& ch : s)
{
if (ch >= '0' && ch <= '9')
{
total = total*radix + ch - '0';
}
else
{
total = total*radix + ch - 'A' + 10;
}
}
return total;
}
十进制转换为任意的n进制数
string intToA(int n, int radix)
{
string res;
do
{
int t = n % radix;
if (t >= 0 && t <= 9)
res += (t + '0');
else
res += (t - 10 + 'a');
n /= radix;
} while (n);
//反转字符串
reverse(res.begin(), res.end());
return res;
}
~未完