Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

c - scanf unknown number of integers, how to end loop?

In class I need to use scanf to get integers to work with. Problem is I do not know to end the while loop. I wait for ' ' in the code, but it is passing all tests. The program has to complete for grading.

How to make code work when input includes several ' ' in input and spacebars at the end of input.

All numbers are given with spacebar between.

# include <stdio.h>

int main()
{
    int numbers;
    char ch;
    int stop = 0;

    while(scanf("%d%c", &numbers, &ch))
    {
        if((ch == '
') stop++;   

        #my_code      

        if (stop == 1) break;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

while(scanf("%d%c", &numbers, &ch)) { if((ch == ' ') .... has a couple of problems.

  1. If the line of input has only white-space like " " or " ", scanf() does not return until non-white-space is entered as all leading white-spaces are consumed by "%d".

  2. If space occurs after the int, the " " is not detected as in "123 ".

  3. Non-white-space after the int is discarded as in "123-456 " or "123x456 ".


how to end loop?

Look for the ' '. Do not let "%d" quietly consume it.

Usually using fgets() to read a line affords the more robust code, yet sticking with scanf() the goal is to examine leading white-space for the ' '

#include <ctype.h>
#include <stdio.h>

// Get one `int`, as able from a partial line.
// Return status:
//   1: Success.
//   0: Unexpected non-numeric character encountered. It remains unread.
//   EOF: end of file or input error occurred.
//   '
': End of line.
// Note: no guards against overflow.
int get_int(int *dest) {
  int ch;
  while (isspace((ch = fgetc(stdin)))) {
    if (ch == '
') return '
';
  }
  if (ch == EOF) return EOF;
  ungetc(ch, stdin);
  int scan_count = scanf("%d", dest);
  return scan_count;
}

Test code

int main(void) {
  unsigned int_count = 0;
  int scan_count;
  int value;
  while ((scan_count = get_int(&value)) == 1) {
    printf("%u: %d
", ++int_count, value);
  }
  switch (scan_count) {
    case '
': printf("Normal end of line.
"); break;
    case EOF: printf("Normal EOF.
"); break;
    case 0: printf("Offending character code %d encountered.
", fgetc(stdin)); break;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...