Trent
Trent

Reputation: 11

Netbeans 8.1 scanf() function does not work properly

I'm running Netbeans 8.1 on a Windows 10 x86 64-bit computer, I have the project's Run>Console Type set to Standard Output because neither internal nor external terminal have worked for me with any other source I've made--for which standard output had. In any case, here is the code I'm attempting to run:

int main(void){

float original_amount, amount_with_tax;

printf("Enter an amount: ");
scanf("%f", &original_amount);
amount_with_tax = original_amount * 1.05f;
printf("With tax added: $%.2f\n", amount_with_tax);

exit(EXIT_SUCCESS);
}

and here is the output:

3
Enter an amount: With tax added: $3.15

RUN SUCCESSFUL (total time: 4s)

As you can see, the scan function is reading in the number before the program even prints "Enter an amount:". Also, after I commented out the scanf function, it printed both printf statements as expected. I have been wrestling with this problem for a while now and any help is appreciated, thanks!

Upvotes: 1

Views: 563

Answers (1)

Armali
Armali

Reputation: 19395

ISO/IEC 9899:201x:

Files

… When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. …

Your standard output stream seems to be line buffered, which is most often so.

try printf("Enter an amount: ");fflush(stdout); – BLUEPIXY

That worked! Is this only necessary because I'm using the standard output as my run console?

No, other streams opened by your program may even be fully buffered.

And if so, should I just put it at the beginning of any program that will use a function accessing the buffer?

Putting fflush(stdout) at the beginning of a program won't do, since it outputs only once what is already in the stdout buffer. But you can use setbuf(stdout, NULL) there.

Upvotes: 0

Related Questions