我是C语言的新手,在这里,我有一段代码可以使用do-while循环添加用户输入的任何数字。
例如,如果他们键入1、2、3,最后是0,它应该打印出6。因此,我的问题是如何在不以0结尾的情况下将这3个数字相加。
我的意思是如何让我的代码知道我已经输入了所有数字?
例如:
1
2
3
output: 6
or
10
10
10
10
output: 40
这是我的代码:
#include <stdlib.h>
#include <stdio.h>
static char syscall_buf[256];
#define syscall_read_int() atoi(fgets(syscall_buf,256,stdin))
main()
{
int input;
int result = 0;
do {
input = syscall_read_int();
result = result + input;
} while(input != 0);
printf("%i\n", result);
}
如何在不以0结尾的情况下将这3个数字相加。
你有几种可能性
您可以在EOF上停止(在unix / linux上为control+ d),或者在输入非数字时停止:
#include <stdio.h>
int main()
{
int input;
int result = 0;
while (scanf("%d", &input) == 1)
result += input;
printf("%i\n", result);
return 0;
}
编译与执行:
pi@raspberrypi:/tmp $ gcc -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
1
2 3
<control-d>6
pi@raspberrypi:/tmp $ ./a.out
1 2 3 a
6
pi@raspberrypi:/tmp $
此外,当您仅输入空格或不输入任何内容时,也可以停止 enter
#include <stdio.h>
static char buf[256];
int main()
{
int input;
int result = 0;
while ((fgets(buf, sizeof(buf), stdin) != NULL) &&
(sscanf(buf, "%d", &input) == 1))
result += input;
printf("%i\n", result);
return 0;
}
请注意,每条输入线仅使用一个数字,因此大小为256的缓冲区非常大
编译与执行:
pi@raspberrypi:/tmp $ gcc -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
1
2
<enter>
3
pi@raspberrypi:/tmp $ ./a.out
1 2
q
1
pi@raspberrypi:/tmp $
等等
我建议您不要使用atoi
,如果输入的数字无效,则该值会默默地返回0,例如,您可以scanf
像我一样检查返回值,或者strtol
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句