Simple C

Associate
Joined
22 Jan 2005
Posts
186
Hello all,

I've just created a very simple C program in Windows that works fine inside my IDE (Code::Blocks), but once it has been compiled, and I run the program it quits after I have input some numbers. :(

It works fine on my Mac. Blah.

Thanks in advance.
 
Please post code.

Chances are its just ending execution because it has nothing left to do (and hence on windows closing the console).

Try reading in a character before the end of your main function, like

printf("Press enter to continue...");
fgets(...); // blocks the termination of program till enter is pressed
return 0;
 
Hey thanks for replying. Code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
int a, b, c;
int y;
double average;
printf("This program will calculate the mean average of 3 numbers.\n");
printf("To continue, press 1 and then enter.\nTo exit press 0 and then enter.\n");
scanf("%d", &y);
if (y==0) {
printf("Program will now exit.\n");
exit(1);
}
else {
printf("Please enter three integers between 0 and 100\n");
printf("and I will work out their mean average.\n");
do {
scanf("%d %d %d", &a, &b, &c);
break;
}
while (a>=1 || a<=99 || b>=1 || b<=99 || c>=1 || c<=99);
if (a<1 || a>99 || b<1 || b>99 || c<1 || c>99) {
printf("Numbers are not in valid range, please restart program.\n");
exit(1);
}
else {
average=(a+b+c)/3.0;
printf("The average of these numbers is %g.\n", average);
}


}

return 0;

}
 
Yep, so you program is just terminating when it displays the average of the numbers (because it has nothing else to do). On Windows this typically closes the window as you describe.

So make it require a user action to terminate instead i.e

Code:
char endc[10];
scanf("%s", &endc); // waits for user input

return 0;

Or, go to start->run->cmd then execute your program manually and it will appear the same as on OSX.
 
Back
Top Bottom