用C语言结束do-while循环

时间:2020-05-10 14:31:46

标签: c loops while-loop do-while

我是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);
}

1 个答案:

答案 0 :(得分:3)

如何在不以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 $ 

此外,当您在输入

前仅输入空格或不输入任何内容时,您也可以停止
#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像我一样检查返回值,或者使用{{ 1}}