I just want to see my output without using any function e.g. Getch ().
is it possible?
Void main()
{
printf(" hello ");
}
CodePudding user response:
Alas, the answer is no, not without adding functions.
But adding functions is the wrong way to do it anyway.
Windows Executable Subprocess Types
Every Windows executable (a PE32) contains a flag that describes the subsystem required to execute it. For most programs it will indicate either GUI or textual/console.
There are other subsystems, but I’ll pretend they don’t exist for this answer.
Most C (and C ) programs containing main()
are textual, requiring a Windows Console (or Windows Terminal) to be attached to it when it is executed.
There are two[1] ways for this to happen:
- You execute the program from an extant console/terminal window, to which the program’s standard I/O is automatically attached. Your program isn’t the only process using that console window, so when it terminates the window remains.
- You execute the program from Explorer (or via some other process), so Windows creates a console/terminal window and attaches your program’s standard I/O to it. Your program is the only process attached to that console, so when it terminates Windows also closes the console window.
[1] There are more than two ways, but I’ll limit the discussion to those two.
Your IDE Is Acting Stupid
When you run it from the IDE you are getting option 2. The IDE ran your program, Windows helpfully created a console window for you, and when your program terminates Windows cleans up by removing the console window.
There are two ways to fix this without modifying your code:
- Tell your IDE to keep the console window open until you press the (in)famous Any key. Many IDEs have this capability. You just need to find it in your IDE’s configuration/settings/whatever.
- Run your program directly from a console window. To get a console window:
- Use Explorer to navigate to where your program’s (newly compiled)
.exe
is. - Click on the Address/URI bar (the one showing the path to the folder you are viewing) and type
cmd
and press Enter. - A new Windows Console will appear!
- Type the name of your program. For example, if my program compiles to
example.exe
then I would typeexample
(with or without the.exe
) and press Enter. - Re-compile and re-use the console for as long as you need. When you are done, either click the big [ X ] button at the top of the console window or type
exit
and press Enter. The console window will disappear.
- Use Explorer to navigate to where your program’s (newly compiled)
That’s all there is to it!
Wow this is a boring-looking answer. Sorry about that.
CodePudding user response:
In C you need to flush to the console in order to print. You can do so by adding '\n' (newline) at the end of the string you're printing. Also make sure to use proper indentation. The following code should work:
Void main()
{
printf("hello\n");
}