可以直接用atoi这个函数
#include "iostream"
using namespace std;
int main()
{
string s="1234";
int n;
n=atoi(s.c_str()); //string对象转成char *,再调用atoi函数
cout<<n<<endl;
}
追问这个确实方便,但是如果我想把s后面还有其他字符(非数字)如:string s="1234sdffs";
而我只想把前四个(1234)转换成整形,怎么弄!
也比较简单,把其中的数字提取出来放在一起,再用atoi
#include "iostream"可以使用库函数atoi。
一、函数名:atoi
二、函数声明:
int atoi(const char *nptr);
三、头文件:
C语言中用stdio.h。
C++中用cstdio。
四、功能:
将字符串nptr中的字符转成数字并返回。具体过程为:
参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零。
五、参数:
nptr, 要转换的字符串。如果为NULL会出错。
六、返回值:
转换后的整型数值。
七、示例代码:
#include <cstdio>