方法一:自己手动实现
#include <iostream>
using namespace std;
int strToint(string s){
int ans = 0;
for(int i=0;i<s.size();i++) ans = ans * 10+ s[i]-'0';
return ans;
}
int main(int argc, char *argv[]) {
int ans = strToint("1234");
cout<<ans;
}
方法二:库函数
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
//先将c++字符串转化为c字符串
string s = "1234";
int ans = atoi(s.c_str());
cout<<ans;
}
注意c_str()返回的是const char*
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
//先将c++字符串转化为c字符串
string s = "1234";
const char* c = s.c_str();
cout<<c[0];
}
如果要对c字符数组做出修改则是不允许的。因此要想转化为可以修改的c字符数组,则需要使用strcpy
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
//先将c++字符串转化为c字符串
string s = "abcd";
int size = s.size();
char c[size];
strcpy(c, s.c_str());
c[0] = 'z';
cout<<c[0];
}
本文介绍了两种在C++中将字符串转换为整数的方法。第一种是通过手动实现逐字符解析并转换;第二种是利用标准库函数atoi,但需先将C++字符串转换为C风格字符串。文中还详细讲解了如何正确处理C风格字符串,避免常见的陷阱。

805

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



