如果需要输入带空格的一行字符串,把scanf()函数改为gets()函数试试。
测试代码如下:
参考链接:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// https://www.runoob.com/cprogramming/c-function-atoi.html
int change(char *s){
int i = atoi(s);
return i;
}
int main(void){
char S[120 ];
// https://www.runoob.com/cprogramming/c-function-gets.html
gets(S);
char m[] = " ";
char *b = strtok(S,m);
char *c = strtok(NULL,m);
int num = change(c);
printf("b=%s,c=%s,%d\n",b,c,num);
return 0;
}
在C语言中,可以使用
atoi()
函数将字符串转换为整数。例如,以下代码将字符串
str
转换为整数:
char str[] = "123";
int num = atoi(str);
如果字符串无法转换为整数,则
atoi()
函数将返回0。需要注意的是,如果字符串中包含非数字字符,则只会将数字字符转换为整数,而忽略其他字符。
问题解答:
将字符串类型转换为数字类型,可以使用C标准库提供的函数atoi()、atof()和sscanf()等。
其中,atoi()函数可以将符合整数表达式的字符串转换为整型变量,atof()函数可以将符合浮点型表达式的字符串转换为浮点型变量,sscanf()函数可以按指定格式从字符串中提取数据。
我们以atoi()函数为例,给出具体的解决方案:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[] = "1234";
int num;
num = atoi(str);
printf("转换后的整数为:%d\n", num);
return 0;
}
输出结果为:
转换后的整数为:1234
说明字符串"1234"已经成功地转换为整数类型。