1.string 转 int
使用stoi或者atoi函数
#include <iostream>
#include<string>
using namespace std;
void main()
{
int x;
string s="123";
x=stoi(s);
cout<<x<<endl;
string s1="123a";
x=atoi(s1.c_str());//遇到字母会停下,若s1中没有数字,则为0
cout<<x<<endl;
string s2="a1";
x=atoi(s2.c_str());
cout<<x<<endl;
}
运行结果

2.int转string
to_string
#include <iostream>
#include<string>
using namespace std;
void main()
{
long long x=123;
string s=to_string(x);
cout<<s<<endl;
}
运行结果

本文详细介绍了在C++中如何将字符串转换为整数,以及如何将整数转换为字符串的方法。通过使用stoi、atoi和to_string函数,可以轻松实现数据类型之间的转换。了解这些转换技巧对于编程实践至关重要。
1231

被折叠的 条评论
为什么被折叠?



