0
votes

I'm a novice programmer getting introduced to C and I'm missing something fundamental about the way my scanf() works. I want to read a single int from the keyboard with code like this:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int userBookSelection;
    scanf("%i", &userBookSelection);
    printf("Printing userBookSelection: %i", userBookSelection);

    return EXIT_SUCCESS;
}

When I run the code, the console stays black until I stop debugging. There is never a cursor waiting for keyboard input. When I stop debug I can see this output in the console, same every time:

Printing userBookSelection: 2130567168

I'm debugging in Eclipse with MinGW GCC compiler on Windows. The code syntax seems to be correct -- is it possible there's something wrong in my build path to make this happen? I need to know why scanf() isn't reading for keyboard input.

1
How are you running the code?SLaks
It works as intended when I run your codeTyler
The program as shown is correct ISO C (up to a point: scanf is broken-as-specified, and should never be used in production -- but for this kind of learning exercise it's fine) and should work as intended. Exactly what compiler, debugger, console, operating system, etc. are you using? Leave nothing out.zwol
I'm using MinGW GCC compiler in Eclipse, Windows 7.J.M.
scanf() returns a value - you should check it.Martin James

1 Answers

0
votes

So I've gotten a line of code from my professor which takes care of this bug -- whether it's a necessary solution particular to Eclipse and/or MinGW I'm not sure. In any case, here's the code with the additional line:

int main(void) {
    int userBookSelection;
    setvbuf (stdout, NULL, _IONBF, 0);//<---The magic line

    scanf("%i", &userBookSelection);
    printf("Printing userBookSelection: %i", userBookSelection);

    return EXIT_SUCCESS;
}

I'd appreciate any additional wisdom on what's going on, what setvbuf() is doing and how scanf() works more fundamentally.