How to handle exception when scanf of integer gets a character

后端 未结 4 397
南笙
南笙 2021-01-21 09:08

The following simple program would give an endless loop when the input is a character, though it meant to tell a character from a digit. How to test if scanf gets a

4条回答
  •  执念已碎
    2021-01-21 09:31

    You should really use TheDubleM's suggestion and check if buffer is numeric and if so use atoi on it. In what I put below you will not detect 8f8 as bad input but just read the 8.

    #include 
    
    int main() {
      int n;
      int return_value = 0;
      char buffer[1024];
    
      while (!return_value) {
        printf("Input a digit:");
        scanf("%1024s", buffer);
        return_value = sscanf(buffer, "%d", &n);
      }
    
      printf("Your input is %d\n", n);
    
      return 0;
    }
    

提交回复
热议问题