两种方法:一种是使用使用atoi函数。第二种是使用格式化输出。
atoi函数:函数原型:int atoi(const char *nptr)
参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零。
附上代码:#include "stdio.h"#include "stdlib.h"#include "conio.h"void main(){char str[1024] = {0}int Intergerprintf("输入一个数字:\n")scanf("%s", str)sscanf(str, "%d", &Interger)printf("转换为整形:%d\n", Interger)getch()}字符串转整数可以有两种方法:
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
*/
在C语言中将字符串转化成整型有两种方法。
1 用atoi函数。
atoi的功能就是将字符串转为整型并返回。其声明为
int atoi(char *str)
比如atoi("1234")会返回整型1234。
2 用sscanf。
sscanf与标准格式化输入函数scanf类似,不过源并非是标准输入,而是字符串。
用sscanf可以处理更复杂的字符串。
比如字符串char * str = "a=1, b=2"
定义int a,b后
可以用
sscanf(str,"a=%d, b=%d",&a,&b)
来将a,b值提取,计算后,a=1, b=2。