c语言中实现输入一个数字字符,然后转换成整数数字输出.怎么做?

如题所述

字符串转整数可以有两种方法:

1.使用c语言自带的库函数:atoi。

函数原型:int atoi(const char *nptr);

功能:把字符串转成整型数。

例如:

#include <stdlib.h>
#include <stdio.h
int main(void)
{
    int n;
    char *str = "12345";
    n = atoi(str);
    printf("int=%d\n",n);
    return 0;
}
/*
输出:
int = 12345
*/

2.可以自己编写一个转换函数:

#include <stdio.h>
#include <stdlib.h>
int atoi(char *s)
{
int t=0;
while(*s){
t=t*10+*s-'0';
s++;
}

return(t);
}
int main ()
{
char a[]="12345";
int n = atoi(a);
printf("n=%d ",n);
return 0;
}
/*
输出:
n = 12345
*/
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-03-18
char c;
int n;
c = getchar();
n = c;
printf(%d,n);
/*也可以直接输出c*/
printf(%d,c);

如果要数字对应输出就这样写
char c;
int n;
c = getchar();
n = c-48;/*48是0的ascii码值*/
printf(%d,n);本回答被网友采纳
第2个回答  2015-03-18
我只知道数据类型能相互转换,但貌似字符和整形无法用一句程序转换吧,如果你想写多句程序来转换,可直接用switch语句,对'0'-'9'进行判断,直接输出0-9,不知道这样行不行的通。追问

不行吧

追答

我是新手,只知道stdio、math,你可以去其他库里找找,有没有直接转的语法,要不数字量庞大的话,确实没法搞。0-9还好,没多少句,如果所有数字就不行了。

第3个回答  2015-03-18
#include追问

。。。。

追答

转换下数据类型就可以啦

追问

怎么转?可以写来吗?