cException when entering a string in language integer input scanf

Asked 2 years ago, Updated 2 years ago, 27 views

#include <stdio.h>
#include <stdlib.h>
int main()
{
  int num = 0;

  while(1) {
    printf("number : ");
    scanf("%d", &num);
    printf("%d\n", num);
    num = 0;
  }
}

If you enter a non-integer string here, is there a way to receive it again without going around an infinite loop?

c

2022-09-22 13:52

1 Answers

As a traditional (?) solution, there are codes as follows.

 while (getchar() != '\n');

To give you a brief explanation of the principle, The function scanf switches to a state where you can receive input when the input buffer is empty Buffers the value up to the moment the enter is entered.

The buffer value is then extracted as a variable passed by the factor, such as &num.

However, if the value recorded in the buffer does not match the transmitted variable, The extraction fails, and then the input buffer remains intact, so it falls into an infinite loop.

A function called getchar() is a function that returns a value by reading it from the input buffer. The read value is removed from the input buffer.

Therefore, getchar() also functions to remove the input buffer little by little each time it is called.

When we first enter a value through the scanf function, we end by typing enter, and the last value that enters the input buffer is the value of '\n'.

Therefore, while(getchar()!='\n'; This code will empty the input buffer until the enter value is met value.

After entering the enter, of course, the input buffer is completely empty, and then when you call the scanf function, you switch back to the input state.

It doesn't matter where you put the code.

int main()
{
    int num = 0;

    while(1) {
        while(getchar()!='\n'); // You can put it at the top of the loop like this
        printf("number : ");
        scanf("%d", &num);
        // You can call scanf() right up scanf()
        printf("%d\n", num);
        num = 0;
        // You can put it in at the end of the loop.
    }
}


2022-09-22 13:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.