C++ 数字与字符串之间相互转换(多种方法)
使用系统提供的库函数
1.字符串传数字
(1)、使用stoi()
string s("12345"); long long a = stoi(s); cout << a << endl;
(2)、使用atoi()
char str3[10] = "3245345"; long long a = atoi(str3); cout << a << endl;
(3)、使用 sscanf() 映射
long long c = 0; char str5[10] = "661234544"; sscanf(str5, "%d", &c); cout << c << endl;
(4)、自己写一个简单的
void myAtoi(
char str[],long long& m)
{ int i(0);
int temp = 0;
while(str[i] != '\0'){
temp = temp*10 + (str[i] -'0'); ++i;
}
m = temp;
}
2.数字转字符串
(1)、使用c++里的to_string()
long long m = 1234566700; string str = to_string(m); cout << str << endl;
(2)、使用itoa()
int n = 100; char str2[10];
itoa(n,str2,10); cout << str2 << endl;
(3)、使用sprintf() 映射
long long b = 1234560; char str4[10] = {0}; sprintf(str4, "%d", b); cout << str4 << endl;
(4)、自己写一个简单的
void myItoa(long long n, char str[])
{
char temp[MAX]{0};
int i(0);
int j = 0;
while(n){
temp[i++] = n%10 + '0';
n /= 10;
}
cout << temp << endl;
while(i>0)
str[j++] = temp[--i];
cout << str << endl;
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_43971252/article/details/104063490