【问题标题】:End of do-while loop in C languageC语言中do-while循环的结束
【发布时间】:2020-08-26 01:10:06
【问题描述】:

我是 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来表示结束?
  • 当普通函数可以工作时不要使用#define
  • 不确定是否了解您。如果您真的不想添加 0,只需执行 while 而不是 do whilewhile ((input = syscall_read_int()) != 0) result ++ input; 如果您不想管理 0 情况,如何检测 EOF? atoi 不是一个好选择,输入一个非数字,你会循环到世界末日……或者关机
  • 您正在输入fgets,因此您可以在有空行时结束。您已将其隐藏在 define 中。把它放在代码中。

标签: c loops while-loop do-while


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2016-08-24
    • 2018-04-06
    • 2022-01-03
    相关资源
    最近更新 更多