printf not printing on console - c

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

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 STDOUT from within gdb

I have a function that pretty prints a data structure, its function prototype is:
void print_mode(FILE *fp, Mode *mode);
the FILE* allows you to redirect the output to anywhere you want, e.g. stdout, stderr, a file etc. Mode is the data structure
I am trying to call this function from within gdb and want the output to be directed to the gdb console window, stdout?
I have tried:
(gdb) p print_mode(STDOUT,fragment_mode)
No symbol "STDOUT" in current context.
(gdb) p print_mode(stdout,fragment_mode)
$17 = void
neither of which work
any ideas how i can get the output of the function to display in the gdb console?
should add - I am using gdb within emacs 24.2.1 under linux
STDOUT seems to be macro, which is not know to GDB, as handled prior to compilation by the pre-preprocessor.
Using stdout should do the job.
However the function print_mode() simply does not seem to print out anything.
In terms what's being printed to the console by the program being debugged, GDB's commands printand call should not make a difference.
For details on this you might like to read here: https://sourceware.org/gdb/onlinedocs/gdb/Calling.html
An issue might be that stdout by default is line buffered, so output would not occur before detecting a linefeed and print_mode() perhaps does not send a linefeed (\n).
To test this just use stderr as output file, as the latter isn't buffered:
p print_mode(stderr, fragment_mode)
Oh dear - silly mistake. You're right, stdout does do the job.
I forgot that having upgraded from emacs 23 to 24, the way gdb works has changed in as much as it now opens a separate buffer *input/output of program-name* to which it redirects the output of the program being debugged. In the prior version of emacs it was all displayed in the same, single gdb buffer.
So my second attempt was actually working, I was just looking in the wrong place so didn't see the output

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!

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.

Resources