繁体   English   中英

C 语言中的 do-while 循环结束

[英]End of do-while loop in C language

我是 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 $ 

另外你也可以在输入前只输入空格或什么都不输入时停止

#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 $ 

ETC

我鼓励您永远不要使用atoi ,如果输入无效数字,它会默默返回 0,您可以使用例如scanf像我一样检查返回值,或者strtol

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM