简体   繁体   中英

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

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 .

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.

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.

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);

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".

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.

您想使用\\r\\n而不是\\n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM