Search code examples
cstdio

getchar having trouble reading due to scanf fail


#include <stdio.h>

int main() {
    float f;
    char s;
    if (scanf("%f", &f) == 1) {
        printf("%f", f);
    }
    else {
        s = getchar();
        printf("'%c'", s);
    }
}

This works for floats, and when I enter '*' or '/'. Why does this not work for '+' and '-'?

 ./a.out 
*
'*' 

This is the output, and this is what I want. But in case of '+'

./a.out
+
'
'

This is happening and I want '+' to be the output.

Seems like scanf's failure somehow interferes with the getchar()


Solution

  • + is a valid char to start a float value, so scanf will consume it before failing because there is no number coming after +.

    Then getchar will read the next char after + which is the \n newline.

    If you want to catch the leading + (or -) in inputs that are not valid float values, such as "+\n" or "-xyz", then you'll have to read it as string then parse it after that, for example with sscanf, and use it as a string if it doesn't parse as a float.