Computer Science Canada

Why do i have to write getchar() to get an output?

Author:  lastlegion [ Tue Mar 16, 2010 9:34 am ]
Post subject:  Why do i have to write getchar() to get an output?

Hey! I am kinda new to C...I am a bit confused with the usage of getchar()
i know it is used to get a character input from the user...and thats how i use it when i am developing in linux.
But when I use windows - Devc++...i have to write a getchar() statement at the end of my program or else I dont get any output. Why is it so?

Author:  Dan [ Tue Mar 16, 2010 9:37 am ]
Post subject:  RE:Why do i have to write getchar() to get an output?

It's likely that you are getting input however the windows is closing to fast for you to see it.

If you try running your exe file in the command line rather then just clicking on the exe (or threw any IDE you are using) it will likely show the output.

Also many IDEs have a setting to pause after a complied exe is ran to avoid this issue.

Author:  lastlegion [ Tue Mar 16, 2010 9:54 am ]
Post subject:  Re: RE:Why do i have to write getchar() to get an output?

Dan @ Tue Mar 16, 2010 8:07 pm wrote:
It's likely that you are getting input however the windows is closing to fast for you to see it.

Could you elaborate that?

And yeah, i tried running the exe from command line and it worked fine Smile

Author:  DtY [ Tue Mar 16, 2010 11:16 am ]
Post subject:  Re: RE:Why do i have to write getchar() to get an output?

lastlegion @ Tue Mar 16, 2010 9:54 am wrote:
Dan @ Tue Mar 16, 2010 8:07 pm wrote:
It's likely that you are getting input however the windows is closing to fast for you to see it.

Could you elaborate that?

And yeah, i tried running the exe from command line and it worked fine Smile
When you double click on an exe to start it in windows, the command prompt closes as soon as the program finishes, which is usually not enough time to see the output.

By using getchar() at the end, it makes the program sit until there is more input from the user (they hit enter), which means that the program doesn't actually end until you hit enter, so the window stays open and you can see it.

When you run it from the command prompt, it returns to the shell after, which keeps the window open.


: