简体   繁体   English

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

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

I'm new to the language C and here I have a code to add any number the user inputs using a do-while loop.我是 C 语言的新手,在这里我有一个代码可以使用 do-while 循环添加用户输入的任何数字。

For example if they type in 1, then 2, then 3, and finally 0, it should print out 6. So, my question is how to add these 3 numbers without ending the input with 0.例如,如果他们输入 1,然后是 2,然后是 3,最后是 0,它应该打印出 6。所以,我的问题是如何在不以 0 结尾的情况下添加这 3 个数字。

I mean how can I let my code know that I have inputted all the numbers I have?我的意思是如何让我的代码知道我已经输入了所有的数字?

For ex:例如:

1
2
3
output: 6

 or 

10
10
10
10
output: 40

This is my code:这是我的代码:

#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);
}

how to add these 3 numbers without ending the input with 0.如何在不以 0 结尾的情况下添加这 3 个数字。

you have several possibilities你有几种可能性

you can stop on EOF ( control + d on unix/linux) or when a non number is enter:您可以在 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;
}

Compilation and execution:编译和执行:

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 $ 

In addition you can also stop when you enter only spaces or nothing before 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;
}

note that time only one number is used per input line, and a buffer sized 256 is very large for that请注意,每个输入行只使用一个数字,并且大小为 256 的缓冲区非常大

Compilation and execution:编译和执行:

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 ETC

I encourage you to never use atoi , that one silently returns 0 in case a non valid number is enter, you can use for instance scanf checking the return value as I did, or strtol我鼓励您永远不要使用atoi ,如果输入无效数字,它会默默返回 0,您可以使用例如scanf像我一样检查返回值,或者strtol

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

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