Inputting float into a program that only deals with ints

后端 未结 3 1903
星月不相逢
星月不相逢 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条回答
  • 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 */ }
    
    0 讨论(0)
  • 2020-12-07 03:30

    It looks like scanf() is reading your "3" in the second case, and ignoring the "9".

    Then when the second scanf() is called, there is already text in the input buffer (the ".9").

    I can't tell exactly what it's doing with the ".9". It may have found the dot and just aborted there with b uninitialized. It should be a simple matter to determine what is happening by stepping through with the debugger.

    But, basically, not all the input is being processed by the first call to scanf() and so that's what the second call is trying to read. And that's why it's not waiting for you to input any data for the second call.

    0 讨论(0)
  • 2020-12-07 03:32

    If the next character that is to be read cannot be converted under the current format as specified by the Format Specifier, scanf stops scanning and storing the current field and it moves to the next input field (if any).

    And that particular character is treated as unread and used as the first character of next input field or any subsequent read operation.

    In the example given above, it is scanning 3 and then cannot resolve . to the format specifier "%d". Hence it stores 3 in variable a leaving .9 as unread. The control when passes to the next scanf statement, it scans ., but again as it cannot resolve . to format specifier "%d", it skips the input scanning for that field.

    Now as variable b was not assigned, it contains some garbage value. And any arithmetic operation with garbage values result into garbage values.

    0 讨论(0)
提交回复
热议问题