字符串和整数互转
字符串使用string
类
方法 1
int my_string_to_int(string s)
{
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
sum = sum * 10 + (s[i] - '0');
}
return sum;
}
string my_int_to_string(int n)
{
string s;
int i = 0;
int j = 0;
char t;
while (n != 0)
{
s.push_back(n % 10);//字符转整数
n /= 10;
i++;
}
i--;
while (j < i)//反转字符串
{
// t = s[i];
// s[i--] = s[j];
// s[j++] = t;
swap(s[i--], s[j++]);//交换字符
}
return s;
}
方法 2
stringstream
类
#include <sstream>
stringstream ss;
string s;
int n=123;
ss<<n;
ss>>s;
方法 3
字符串输入输出流
#include <iostream>
int n;
char t[100];
sscanf(n,"%d",t);
ssprintf(t,"%d",n);
方法4
#include<iostream>
int n=123;
char t[100];
cout<<to_string(n)<<endl;
cout << "to_string " << to_string(n) << endl;
cout << "itoa " << itoa(n, t, 10) << endl;
cout << "ltoa " << ltoa(n2, t, 10) << endl;
cout << "atoi " << atoi("123") << endl;
cout << "atol " << atol("123") << endl;
//字符串转各类数
cout << "stoi " << stoi("123") << endl;
cout << "stol " << stol("123") << endl;
cout << "stof " << stof("123") << endl;
cout << "stod " << stod("123") << endl;