Netbeans 8.1 scanf() function does not work properly - c

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!

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.

Related

Why my little C game ignore player's first attempt? [duplicate]

This question already has answers here:
Why doesn't getchar() wait for me to press enter after scanf()?
(10 answers)
Closed 3 years ago.
I'm learning programmation in C and tried to create a program that asks the user his age. When the user writes his age (for example 18) he gets the message "So you're 18 years old". When I execute the .exe file it automatically closes after you see the message, so fast that you don't see it. Then I added getchar so that the user reads the message and then presses Enter to quite. Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age=0;
printf("How old are you?\n");
scanf("%d",&age);
printf("So you're %d years old", age);
getchar();
return 0;
}
Unfortunately, when I execute the .exe file, it still closes automatically like if the getchar() doesn't exist and I don't know why.
scanf("%d",&age);
When the execution of the program reaches the above line,you type an integer and press enter.
The integer is taken up by scanf and the \n( newline character or Enter )which you have pressed remains in the stdin which is taken up by the getchar().To get rid of it,replace your scanf with
scanf("%d%*c",&age);
The %*c tells scanf to scan a character and then discard it.In your case,%*c reads the newline character and discards it.
Another way would be to flush the stdin by using the following after the scanf in your code:
while ( (c = getchar()) != '\n' && c != EOF );
Note that c is an int in the above line
You're only having trouble seeing the result because you're starting the program from a windowing environment, and the window closes as soon as its internal tasks are completed. If you run the compiled program from a command line in a pre-existing shell window (Linux, Mac, or Windows), the results will stay on the screen after you're returned to the prompt (unless you've ended by executing a clear-screen of some sort). Even better, in that case, you don't need the extraneous getchar() call.
For Windows, after opening the command prompt window, you'd issue a "cd" command to change to the directory that contains the compiled program, and then type its name. For Linux (and, I presume, Mac, since Mac is UNIX under the hood), you'd need to type ./ ahead of the program name after changing to the appropriate directory with "cd".

Printf not working with scanf

Hi i am new to the programing and for example in my code:
#include <stdio.h>
int main (void){
int a;
printf("Write a number: ");
scanf("%d", &a);
printf("Your written number was: %d", a);
return 0;
}
Printf does not write "write a number" in console when i start the program but only after i already inserted the number and pressed enter.
I have already done some research and found out for this code:
setvbuf(stdout, NULL, _IONBF, 0);
when i paste this into my program it works as it should but i am wondering why do i have to do that?
when i paste this into my program it works as it should but i am
wondering why do i have to do that?
It's because printf() is usually line-buffered when attached to a terminal. So disabling the buffering with the call to setvbuf() makes stdio library to not buffer at all.
You can also use fflush(stdout); after the printf() call to flush out the buffered output. The same can be done with setbuf(stdout, NULL); as well.
You can also add a \n at the end of printf() statement to force the flushing. But this will work only if the output goes to a terminal device.
For example, if you do (on a unix-like system):
./a.out > output_file
then the \n will not flush the buffer.
Out of the two options (setbuf() and fflush()),fflush(stdout); is probably the better option in most cases. Since disabling the buffering completely can have negative impact on performance (which is the primary reason for buffering in the first place) whereas fflush() can be judiciously used at the right place when you think it's necessary.
printf has a buffer. It is a mechanism to make code run faster by not having to switch between the user context and the kernel context. To get over this you can tell the code to flush the buffer - i.e. send it to the operating system. This can be done by
fflush(stdout);
After a printf. If the printf contains a new line this is done automatically.
You probably want \n in each of those printf statements.
Add linefeed "\n" to your printf lines like so:
printf("Write a number: \n");

Eclipse CDT unexpected output after compiling C Program

While Trying this code on eclipse CDT with GCC 5.1.0 Compiler
All the strings were printed after the user input ..
and while compiling it on Visual Studio and Code Blocks IDEs even with the windows CMD The program worked just fine as expected ..
‪#‎include‬ <stdio.h>
static char string[128] = "";
int main() {
printf("Type a string: ");
scanf("%s",string);
printf("The String is %s", string);
return 0;
}
Eclipse Output:
Visual Studio Output:
Thanks ,,,
OK, I see now. I think the issue is that whenever you want to be certain that something is printed by a given point in the code, you need to flush stdout at that point.
Otherwise, streamed contents can be queued and delivered in an implementation-dependent way (usually in small batches)
The C standard library's printf(), when outputting to stdout and encountering a newline \n, provides an implicit flush, so you don't need to call flush() yourself. Whereas with C++'s std::cout, only std::endl has this property; \n is not guaranteed to.
Deliberately flushing stdout in C can be done like so: fflush(stdout);
See also: Why does printf not flush after the call unless a newline is in the format string?

getchar not taken in consideration after scanf [duplicate]

This question already has answers here:
Why doesn't getchar() wait for me to press enter after scanf()?
(10 answers)
Closed 3 years ago.
I'm learning programmation in C and tried to create a program that asks the user his age. When the user writes his age (for example 18) he gets the message "So you're 18 years old". When I execute the .exe file it automatically closes after you see the message, so fast that you don't see it. Then I added getchar so that the user reads the message and then presses Enter to quite. Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age=0;
printf("How old are you?\n");
scanf("%d",&age);
printf("So you're %d years old", age);
getchar();
return 0;
}
Unfortunately, when I execute the .exe file, it still closes automatically like if the getchar() doesn't exist and I don't know why.
scanf("%d",&age);
When the execution of the program reaches the above line,you type an integer and press enter.
The integer is taken up by scanf and the \n( newline character or Enter )which you have pressed remains in the stdin which is taken up by the getchar().To get rid of it,replace your scanf with
scanf("%d%*c",&age);
The %*c tells scanf to scan a character and then discard it.In your case,%*c reads the newline character and discards it.
Another way would be to flush the stdin by using the following after the scanf in your code:
while ( (c = getchar()) != '\n' && c != EOF );
Note that c is an int in the above line
You're only having trouble seeing the result because you're starting the program from a windowing environment, and the window closes as soon as its internal tasks are completed. If you run the compiled program from a command line in a pre-existing shell window (Linux, Mac, or Windows), the results will stay on the screen after you're returned to the prompt (unless you've ended by executing a clear-screen of some sort). Even better, in that case, you don't need the extraneous getchar() call.
For Windows, after opening the command prompt window, you'd issue a "cd" command to change to the directory that contains the compiled program, and then type its name. For Linux (and, I presume, Mac, since Mac is UNIX under the hood), you'd need to type ./ ahead of the program name after changing to the appropriate directory with "cd".

Ambiguous behaviour of printf() with Eclipse

I am a newbie to buffered streams.I was write a simple c program which takes a string as a user input and displays it back.My working environment is eclipse under windows.The code is as follow:
#include<stdio.h>
enum { max_string = 127 };
static char string[max_string+1] = "";
void main(){
printf("type the input string---> \n");
fgets(string,max_string,stdin);
printf("the input string was ---> %s\n",string);
}
While running it,the user input is taken first and the two printf()'s are executed after.
The output sample is:
user input
type the input string--->
the input string was ---> user input
I tried the upper code in CodeBlocks IDE and it worked fine.The output is as follow:
type the input string--->
user input
the input string was ---> user input
What is the problem?
I also added a \n at the last of my printf() so as to flush them immediately.
Regards.
stdout is line-buffered only if connected to a terminal. Eclipse's terminal-emulation might not be detected as terminal.
From man stdout:
The stream stdout is line-buffered when it points to a terminal.
There are several way to get around this limitation:
call fflush(stdout) every time output shall appear
set stdout to be unbuffered by using setvbuf() like this
setvbuf(stdout, NULL, _IONBF, 0);
prior to using stdout.
use stderr which isn't buffered by default
OK!! after some googling i found out that the eclipse terminal emulator do more buffering than the normal terminal.We need to do fflush(stdout); after the printf to make it working.

Resources