PDA

View Full Version : Question about printf and scanf.


cparadis6191
01-29-2010, 03:31 AM
Hi guys,
I'm in a C programming class (just starting the class) in college and I'm having a little problem. I usually use eclipse at the machines running Fedora 12 at school. I set up eclipse on my home pc (running 7) with MinGW and msys as a compiler. To test to see if my compiler was working I wrote the following code... What I want to show up is something like this.

Run code:
Input a value to be printed: 123
a = 123

What happens is this:
123
Input a value to be printed:
a = 123

The first printf statement happens after I input the value... do different compilers have different priorities for functions? specifically printf and scanf? thanks in advance.

Here's the code.

#include<stdio.h>
int main()
{
int a;

printf("Input a value to be printed:\n");
scanf("%d", &a);
printf("a = %d", a);

return 0;
}

oracleguy
01-29-2010, 06:08 AM
There is no such thing as function priority like you are thinking. The functions are executed in the order entered in the program.

As for your program, the code you posted works the way you want when I try it. I tested it on Windows 7 and Linux. Are you sure you put the scanf after the printf when you compiled the program?

Zoglarfy
02-27-2010, 06:03 AM
I'm running into the exact same problem in the exact same setup (except I'm on Windows XP). Wrote a simple program just to see if it would work, and no matter what, it seems to await input from the scanf statement before doing anything at all.

Here's my code:
#include <stdio.h>

int main( void )
{
int intvar = 3;
printf("The address of intvar is %p.\n",&intvar);
printf("\nEnter an integer: ");
scanf("%d", &intvar);
printf("The value you entered was %d.\n",intvar);

return 0;
}


Here's the output (the 4321 was my input):
4321
The address of intvar is 0022FF54.

Enter an integer: The value you entered was 4321.
Anyone have any ideas?

ffmast
02-28-2010, 02:23 PM
I have tried this program at my localbox (redhat) , and it worked fine.
Maybe ,from some weird reason, the output on your system is buffered, and not shown right away. Try adding

fflush(stdout);

before scanf("%d", &intvar);