Reputation: 12484
This is a self-help program I made for useful break activities. At the end of it need to type a number, then press "enter" to restart. I'd rather have to only type anything, or any number.
#include <stdio.h>
#include <stdlib.h>
main()
{
int i;
srand((unsigned)time(NULL));
i = rand();
int k;
k = (int)i%22;
printf("\n\n");
switch(k){
case 0: printf("%\t Weather"); printf(" weather"); break;
case 1: printf("\t Hand exercises ok"); break;
case 2: printf("\t BR break"); break;
// etc etc
case 15: printf("\t ~~ DOODLE ON PAPER ## "); break;
case 16: printf("\t Practice Mental Math "); break;
case 17: printf(" \tgo to SNOPES.com\t"); break;
case 18: printf("\t Browse JAVA API"); break;
case 19: printf("\t Left handed writing"); break;
case 20: printf("\tGo outside OUTSIDE\t"); break;
case 21: printf("\tCall M&K\t"); break;
case 22: printf("TRASH CAN BBALL\t"); break;
}
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
long g;
scanf("%d", &g);
if(g >0){
system("cls");
main();
}
system("pause");
}
I use this as a simple Windows App. If there are other issues/problems I'm totally open to criticism as I'm still new to C. I appreciate any tips or advice.
Upvotes: 1
Views: 3306
Reputation: 881653
First off, you shouldn't be calling main
at any point in your code. If you want to restart, simply code up a loop that continues until the termination condition. I can't recall whether recursively calling main
is valid according to the standard but, even if it was, you risk crashing due to uncontrolled recursion.
If you want to allow empty entry (just the ENTER key) to terminate input, you can use fgets
to get a line (empty or not), then evaluate that.
I always point people towards my robust user input function and, if you use that, you can simply code up something like:
// Force initial entry into loop
int rc = RC_NO_INPUT;
char buff[] = {`x', '\0`};
:
// Run loop until empty input.
while ((rc == OK) && (*buff != '\0')) {
// Do whatever you need to do here.
// Get input, 'while' loop will check it.
rc = getLine ("ENTER to exit, anything else to continue: ",
buff, sizeof (buff));
}
Upvotes: 1
Reputation: 2976
main is a function like any other. There is nothing special about it except the C Runtime's startup function (usually called 'start()' sets up parameters and calls it. Go nuts.
Especially in your case where you didn't care about argc/argv.
Anyways - your real problem is that stdin is line oriented by default - so any getc/getchar/scanf is going to be buffered until a carriage return. There are various ways of undoing this based on the OS.
setvbuf() and friends can change the buffering, but it may not work depending on your OS because the underlying file handles of the system may remain buffered.
Some OS's have other functions like kbhit(); (not ansi) or the like. Sorry it's not a solid answer - what's your OS?
Upvotes: 1