Reputation: 37
I'm programming in C and I download code block IDE because it's easier to use. As you know, the minimal code in C is to write: Hello World in a CMD window. When I try to launch the program via code block, it works but when I open the .exe
file directly, it open and close quickly. Can someone explain me why?
#include <stdio.h>
int main() {
int age = 0;
printf("how old are you?");
scanf("%d", &age);
printf("You are %d", age);
getchar();
return 0;
}
Upvotes: 1
Views: 611
Reputation: 2534
I am guessing your program looks something like this:
#include <stdio.h>
int main()
{
printf("Hello, world!\n");
}
The program prints Hello, world!
to the screen and then ends because it has nothing left to do.
A simple fix to this is to add the function getchar()
after the printf
statement. This will cause the program to wait for any user input before closing. It stands for get character
.
Your new program should look like this:
#include <stdio.h>
int main()
{
printf("Hello, world!\n");
getchar();
}
#include <stdio.h>
int main() {
int age = 0;
printf("how old are you?\n");
scanf("%d", &age);
getchar();
printf("You are %d.\n", age);
getchar();
}
Upvotes: 1
Reputation: 11237
Put a getchar()
as the last line of main:
int main()
{
// code
getchar();
return 0;
}
Upvotes: 0
Reputation: 5421
What I think you're describing is the OS destroying the temporary command window when the program is done executing. Try opening a command window yourself, and then running your .exe from there. Alternatively, use int t; scanf("%d", &t)
(or something) to keep your program from finishing, thus holding the window open
Upvotes: 1