running a program in Unix vs in Windows - c

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.

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

Related

The output in VS code doesn't appear in terminal

i have used debugger and try to debug simple program but no output appear in terminal
photo of the program:
If program was well compiled - then you are a victim of buffered stdout stream, that is used by default with printf function.
Changing call to add \n at the end will solve the problem for you. printf("your tex\n").
See this SO post to understand background: Why does printf not flush after the call unless a newline is in the format string?

C/C++ BEGINNER - fgets with stdin causing unexpected 'loop' results

I'm a programming student who's only really looked at Java up until now. This semester is our first time using C and I'm having a lot of trouble wrapping my head around some of the simplest functions. I really have no idea what I'm doing. I couldn't even get Eclipse to work correctly with MinGW so I eventually gave up and reverted to Netbeans.
So basically I'm trying to use fgets to read user input for a switch-case menu, but I can't get fgets to work in even the simplest situations. To troubleshoot I tried copying a simple fgets example from online, but even that is giving me unexpected results.
When I run the code below it just runs an infinite empty loop (it does not prompt for user entry at all, it does not accept any user entry, it just 'runs' forever and the console remains blank). When I delete the fgets line and remove the other reference to the 'name' variable it works as you would expect (prints the user entry prompt and then ends).
Example code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char name[10];
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s.\n",name);
return(0);
return (EXIT_SUCCESS);
}
Any advice would be appreciated!
Other info:
I am running - Win 8 (poor me) & Netbeans IDE 8.0 (with MinGW)
When creating my C project I select File=> New Project=> C/C++=> C/C++ Application
EDIT: When I run the program I have tried:
1) right clicking the project file => Run; and
2) clicking the big green arrow in the netbeans ribbon;
.... neither works.
This code should work, but for you to be able to input anything, you need to run in in a proper terminal.
My guess is that you're running it inside your IDE and it's set to use pipes as stdin/stdout. Instead you should start cmd.exe and run the program in there (you'll have to navigate to the correct directory first).
Or, optionally, there might be a setting in your IDE to run the program using cmd.exe or with a builtin terminal.
A final note. You should learn to use sizeof whenever a buffer size is required. I.e. change this:
fgets(name,10,stdin);
to
fgets(name, sizeof(name), stdin);
Also, please use spaces to make your code more readable. Reading code is a big part of programming.
1) You might want to flush the file, after printf("Who are you? "); with fflush(stdout);
2) You have two return statements (which is harmless).
Other than that, your code is fine.
It works perfect - but you might want using fflush(stdin); before the fgets() call.
Also remember fgets return a string with '\n' after a user input - solved simply with name[strlen(name)-1]='\0'; - which is basically putting NULL as an "end of a string" symbol, basically you remove the '\n'.
And DO NOT change 10 to sizeof(name) - it doesn't matter at all, basically it's even supposedly worse as you can't use this in functions properly (sizeof(name) won't always match the length and would be the size of the pointer).
You should try compiling with MinGW if it didn't work, it will surely work on it.
A reminder: fgets() may let you enter MILLION characters, but it will take the first 10, in this case, at least.

Using C and trying to create a mad lib.

As my title says I'm a new programmer learning C. This is my second day programming and I need help fixing this problem in my code. I'm making a mad lib and while no errors come up the first scanf takes 2 lines rather than the 1 every other scanf uses.
Here's the code:
#include <stdio.h>
int main()
{
char verb[20];
char loc[20];
char noun1[20];
char noun2[20];
char adj[20];
/* The following is the part where you input words. It sets them as strings (named word1-5, as stated above)*/
printf("Welcome to Mad Libs! \nAnswers can only be one word long. \nPlease enter a verb.\n");
scanf("%s\n",verb);
printf("Now enter a location!\n");
scanf("%s\n",loc);
printf("Now enter a noun!\n");
scanf("%s\n",noun1);
printf("Now enter another noun!\n");
scanf("%s\n",noun2);
printf("Now please enter an adjective!\n");
scanf("%s\n",adj);
/* It all comes together here. The code is supposed to take the strings set previously and put them into this story. */
/* The dashes and various /n's are there to make the final Mad Lib easier to read */
printf("\n\nHere is your Mad Lib:\n------------------------------ \nHolly %s down to the %s.\nOnce she got there she bought some %s and ate it!\nAfterwards, Holly brought it home and let her %s eat it.\nHolly is a %s girl!\n------------------------------ \n",verb,loc,noun1,noun2,adj);
return 0;
}
It was made using a combination of Vi and Sublime Text 2 on Ubuntu.
Like I said, I'm not getting any errors when compiling and everything seems to be in order, the problem is that once I run it in the Terminal I have to enter the first answer (answer to "Welcome to Mad Libs! Answers can only be one word long. Please enter a verb.") twice and it takes both of them.
Please try running it yourself (it should work in both OS X and Linux as a .c file) if you're confused as to what I mean, I honestly don't know how to describe the error very well. It makes me input the first answer twice and causes problems when showing the final mad lib.
Just use scanf("%s", ...), not scanf("%s\n"). The \n doesn't get there until later. (Oh, and this is also a good way to get buffer overflows, by the way, so you might consider using fgets, et. al.)
The way it's working right now is:
You type a line and press Enter. scanf gets the line, but without the \n, so it's still waiting.
You type the next line and press Enter. scanf now has the \n at the end of the previous line and uses that string. The first line was read, the second line is now in the buffer, and scanf is awaiting another \n that already exists.
GOTO 2
And that has the effect of shifting all of the answers by one.

printf not printing on console

I’m getting started in the C language. I am using eclipse (juno) as my IDE and installed CDT plugin. I have also unpacked mingw64 (GCC Compiler). I wrote a very simple program to see if it works. This is my code:
#include <stdio.h>
int main()
{
int age;
printf("Hello, please enter your age:\n");
scanf("%d", &age);
printf("Your age is %d", age);
return 0;
}
The problem is that the output buffer is filled with the string value of the first printf but does not output it to the console. I have to enter a number, and only then the buffer pours all the data to the console so I see the console something like this:
1
Hello, please enter your age:
Your age is 1
instead of what is expected that is:
Hello, please enter your age:
1
Your age is 1
Now, I found that I can use fflush(stdout) after the first printf but I don't think that this solution is elegant and even necessary. Any ideas on how I can overcome this?
EDIT - because I'm learning this in my university, I can't use anything that wasn't learned in the course so I can only use printf and scanf
NEW EDIT - I think I have found an explanation for this. As I said, I am outputting to the console view inside Eclipse. The strange thing is that if I compile and run the program from the command line of Windows, I get the wanted result. Therefore, I think that eclipse is actually writing the output to a file and presenting it in the console window. How can I force eclipse to open a real command line window in my run configurations?
Output is buffered.
stdout is line-buffered by default, which means that '\n' is supposed to flush the buffer. Why is it not happening in your case? I don't know. I need more info about your application/environment.
However, you can control buffering with setvbuf():
setvbuf(stdout, NULL, _IOLBF, 0);
This will force stdout to be line-buffered.
setvbuf(stdout, NULL, _IONBF, 0);
This will force stdout to be unbuffered, so you won't need to use fflush().
Note that it will severely affect application performance if you have lots of prints.
Apparently this is a known bug of Eclipse. This bug is resolved with the resolution of WONT-FIX. I have no idea why though. here is the link:
Eclipse C Console Bug.
You could try writing to stderr, rather than stdout.
fprintf(stderr, "Hello, please enter your age\n");
You should also have a look at this relevant thread.
Try setting this before you print:
setvbuf (stdout, NULL, _IONBF, 0);
As others have pointed out, output can be buffered within your program before a console or shell has a chance to see it.
On unix-like systems, including macs, stdout has line-based buffering by default. This means that your program empties its stdout buffer as soon as it sees a newline.
However, on windows, newlines are no longer special, and full buffering is used. Windows doesn't support line buffering at all; see the msdn page on setvbuf.
So on windows, a good approach is to completely shut off stdout buffering like so:
setvbuf (stdout, NULL, _IONBF, 0);
Add c:\gygwin\bin to PATH environment variable either as a system environment variable or in your eclipse project (properties-> run/debug-> edit)
In your project folder, create a “.gdbinit” text file. It will contain your gdb debugger configuration
Edit “.gdbinit”, and add the line (without the quotes) : “set new-console on”
After building the project right click on the project Debug > “Debug Configurations”, as shown below
In the “debugger” tab, ensure the “GDB command file” now points to your “.gdbinit” file. Else, input the path to your “.gdbinit” configuration file :
Click “Apply” and “Debug”. A native DOS command line should be launched as shown below

C program output in wrong order Eclipse

I have set up Eclipse for c programming on my Windows machine, I have successfully run a "hello, world" program. However, when I try to ask for user input and run the program the console on Eclipse is displaying in the wrong order.
Here is what I have
#include <stdio.h>
int main(void){
char letter;
printf("Please enter a letter:\n");
scanf(" %c, &letter);
printf("The letter you have selected is: %c", letter);
return 0;
}
This program builds just fine, and it runs just fine outside of Eclipse. But when I run it in Eclipse I get the output:
E <--- (this is my user input)
Please enter a letter:
The letter you have selected is: E
I'm not sure why the output is executing in the wrong order, so any help would be much appreciated! Thank you.
Yeah, Eclipse will buffer a certain amount of output (I don't remember how much off hand) before it will appear in the output window. Eclipse is communicating with the attached process through a pipe which is fully buffered. It won't flush until either fflush() is called or the buffer is full. I found that when debugging with Eclipse, things work best if I put the following near the beginning of my application:
setvbuf(stdout, NULL, _IONBF, 0);
This will cause stdout to flush immediately whenever it is written to. If you want to use that for debugging and turn it off otherwise, you can conditionally compile it:
#ifdef DEBUG
setvbuf(stdout, NULL, _IONBF, 0);
#endif
No need to put fflush() everywhere this way.
Edit
Here's where I found the solution when I first ran into this issue myself.
http://wiki.eclipse.org/CDT/User/FAQ#Eclipse_console_does_not_show_output_on_Windows
Eclipse's console is not a true console or terminal but rather eclipse is communicating with the attached process through a pipe which is fully buffered not line buffered. This is why a newline '\n' does not cause the buffer to be flushed.
It sounds like Eclipse is buffering the output of your program and not displaying it right away. This indicates that the "run within Eclipse" feature is not intended to run interactive programs.
You could try adding fflush(stdout); after the first printf, but you shouldn't have to do that just to make your program work in a particular environment.
Try adding fflush(stdout); after the first printf. This has a decent chance of being of help, in case Eclipse does not auto-flush after '\n'.
Yes, fflush()ing buffers is necessary to keep the console's screen updated ...
... but please guys, it's not Eclipse's fault in- and output might get out of sync, but the library's in use!

Resources