简体   繁体   中英

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.

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.

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.

you have several possibilities

you can stop on EOF ( control + d on unix/linux) or when a non number is enter:

#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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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