Hristo
Hristo

Reputation: 46517

running a program in Unix vs in Windows

I'm compiling a simple program written in C and I'm using Eclipse as an IDE, both in Windows 7 and on my MacBook Pro. Very simple program my friend wrote and asked me to help him with:

int a = 0;
char b[2];
printf("Input first class info:\n");
printf("Credit Hours: \n");
scanf("%d", &a);
printf("Letter Grade: ");
scanf("%s", b);

So when I run this on my mac, each line prints and when I encounter the scanf(), I can input and continue as expected. In Windows, I have to input everything and then it will print all the lines. I'm not sure why this is happening... what is the difference b/w Windows and Mac here?

Mac:

Input first class info:
Credit Hours: 4
Letter Grade: B+

Windows:

4
B+
Input first class info:
Credit Hours:
Letter Grade:

Thanks, Hristo

Upvotes: 4

Views: 448

Answers (7)

godlygeek
godlygeek

Reputation: 1549

In addition to the answers about the need for fflush() - your code contains a buffer overflow. The scanf() into b writes 3 bytes - { 'B', '+', '\0' } - and your array doesn't have enough room to store the NUL terminator. You either need a 3 character wide buffer, or to use something other than scanf(%s) with a for reading the 2 characters in.

Upvotes: 0

VonC
VonC

Reputation: 1326576

As mentioned by this thread on Windows:

You need to fflush(stdout) after your call to printf().

Also, because of bug 27663, doing printf() to the Eclipse console doesn't flush until printf()'s buffer becomes full.
That has various associated bugs for Windows console: bug 102043 and bug 121454.

Upvotes: 3

Andy White
Andy White

Reputation: 88385

Like Fyodor said, it's most likely a line-ending problem.

On Windows, the line ending is "\r\n" (carriage-return followed by line-feed).

On Mac OSX, the line ending is just "\r", but "\r\n" also works, because it includes the "\r".

On Unix/Linux the line-ending is usually just "\n".

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95569

My guess is that on Mac OS X, the "\n" causes stdout to be flushed, while this is not so on Windows. Try adding the following piece of code after your print statements and before your scanf statements:

fflush(stdout);

Upvotes: 1

EMP
EMP

Reputation: 62011

Windows and Mac are buffering console output differently. If you want it to appear immediately you need to flush it by calling

fflush(stdout);

after the printf.

Upvotes: 1

RC.
RC.

Reputation: 28257

It's likely due to buffer caching differences.

Try:

fflush(stdout);

before your scanfs. This will force the output to be flushed to the screen when you need to see it.

Upvotes: 1

Fyodor Soikin
Fyodor Soikin

Reputation: 80765

You want to use \r\n instead of \n.

Upvotes: -1

Related Questions