C语言如何把一个字符串转换成数字

如题所述

C语言中,可以使用atoi函数将字符串转换为数字,如atoi("123")可以得到数字123。

atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数,应用在计算机程序和办公软件中。int atoi(const char *nptr) 函数会扫描参数 nptr字符串,会跳过前面的空白字符(例如空格,tab缩进)等。

如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回0。特别注意,该函数要求被转换的字符串是按十进制数理解的。atoi输入的字符串对应数字存在大小限制(与int类型大小有关),若其过大可能报错-1。

扩展资料:

C语言中数字转化为字符串的方案:

使用sprintf函数来实现,如sprintf("%d", 123)可以得到字符串"123"。

sprintf指的是字符串格式化命令,主要功能是把格式化的数据写入某个字符串中。sprintf 是个变参函数。使用sprintf 对于写入buffer的字符数是没有限制的,这就存在了buffer溢出的可能性。解决这个问题,可以考虑使用 snprintf函数,该函数可对写入字符数做出限制。

参考资料来源:百度百科-atoi

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-08-15
C语言有atoi、atol、atof等库函数,可分别把ASCII编码的字符串转化为int、long、float类型的数字。
头文件:stdlib.h
函数原型:int atoi(const char* nptr);
(另外两个类似)

举个例子:
char *str="123";
int num=atoi(str);
执行后,num的值被初始化为123本回答被网友采纳
第2个回答  2013-11-05
#include#include#includechar str[1000];int* change(char *str){ int n,i,j; int *number; n = i = j = 0; while (str[i]) { for (; str[i] && str[i] == ' '; ++i); //找到数字的第一位 for (j = i + 1; str[j] && str[j] != ' '; ++j); //找到数字的后一位 i = j; ++n; } number = (int*) malloc( sizeof(int) * (n+1) );//上面这一段用来分析一共有多少个数,以此分配空间 n = i = j = 0; while (str[i]) { for (; str[i] && str[i] == ' '; ++i); for (j = i + 1; str[j] && str[j] != ' '; ++j); number[++n] = atoi(str + i); i = j; } number[0] = n; return number;}int main(){ gets(str); int *p = change(str); printf("%d\n", p[0]); for (int i = 1; i
第3个回答  2011-07-16
atoi  

C语言库函数名: atoi   功 能: 把字符串转换成整型数.   名字来源:array to integer 的缩写.   原型: int atoi(const char *nptr);   函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字或结束符 \0 时停止转换,返回整型数。
第4个回答  2011-07-16
应用强制转化
例如“char a='A';
int (a);

这样输出的是A的ascii码,值为97。
用atoi() 函数可以的
相似回答