C 语言 atoi()函数
描述
C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。但不适用于string类串,可以使用string对象中的c_str()函数进行转换。
声明
int atoi(const char *str)
返回值
该函数返回转换后的长整数,如果没有执行有效的转换,则返回零。
C++ c_str()函数
语法:
const char *c_str()
描述
**c_str()**函数返回一个指向正规c字符串的指针,内容与string串相同。将string对象转换为c中的字符串样式。
注意:c_str()函数返回的是一个指针,可以使用字符串复制函数strcpy()
来操作返回的指针。
示例
#include<iostream>
#include<cstdlib>
#include<string>
#include<string.h>
using namespace std;
int main()
{
char s[5]="123";
int a = atoi(s);
cout << a << endl; //123
string ss="abcd";
char b[20];
strcpy(b,ss.c_str());
cout<<b<<endl; //abcd
return 0;
}```