Inputting float into a program that only deals with ints

后端 未结 3 1915
星月不相逢
星月不相逢 2020-12-07 02:44

I have a program, but when I input float numbers whenever the program asks for inputs, the program abruptly skips a step and moves onto the end output. The program is below:

3条回答
  •  猫巷女王i
    2020-12-07 03:24

    Console input is line buffered; when you enter 3.9 into a %d format specifier, only the 3 is consumed, the remaining data remains buffered, so the second scanf() call attempts to convert it according to its specifier, it finds a '.' and aborts the conversion leaving b undefined.

    scanf() will continue to "fall-through" until the '\n' at the end of the input data is consumed. You can do this thus:

      printf("Please enter a number: ");
      scanf("%d", &a);
      while( getchar() != '\n' ) { /* do nothing */ }
    
      printf("Please enter a number: ");
      scanf("%d", &b);
      while( getchar() != '\n' ) { /* do nothing */ }
    

    Note that if the format specifier is %c, a modification of the "flush" code is required, because the converted character may already be '\n' :

    scanf("%c", &c);
    while( c != '\n' && getchar() != '\n' ) { /* do nothing */ }
    

提交回复
热议问题