The code below is kinda hard to read, it's a portion of a program I'm trying to make for ANSI DOS. I used fgets and sscanf (only learned about sscanf yesterday - but I see already it rocks), and the program works perfect so far. But I'm curious as to why, when I first tried it, I delcared a char buf[2], figuring that meant that buf[2] = '/0'. Then I had origionally had it where (fgets(buf,1,stdin); - however, when I did, when that part of the program loaded, it would immediatly say "You did not enter a number" - I mean as soon as it came up on the screen, you never had a chance to type anything. Changing it to 2 works just fine, and I know in most examples it's char buf[256], but in this case I'm only receiving one letter, for a menu selection, so I really don't need an array that large. Like I said, it's fixed, I just changed it to 2, and now it works great, but I'd like to know why when you just have fgets read in 1 instead of 2 it does that.
Thanks again,
ash
Code:
void intro() {
cls();
printf("\x1b[31m");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf(" Welcome to Smith Sayings - Freeware Edition\n");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("\x1b[34m");
printf(" Press <ENTER> to continue...\n");
getchar();
printf("\x1b[0m");
return;
}
(Sorry this below is so hard to read, it was too long to retype,
and I copied it from DevC to the clipboard, to here)
void menu() {
int choice;
char buf[2]; <--if you look here, it's 2, then look below
cls();
(skip down reading to right below all the "***********'s")
(that's where the problem is, this stuff in the middle is the main..)
(..menu that I made, which looks horrible posted in this tiny..)
(..window)
printf("\x1b[34m");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf(" ***********Main Menu********** ");
printf(" * * ");
printf(" *\x1b[31m 1)\x1b[34mRun Story * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" *\x1b[31m 2)\x1b[34mAbout * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" *\x1b[31m 3)\x1b[34mExit * ");
printf(" * * ");
printf(" ****************************** ");
printf("\n\n\n\n");
printf(" Choice:");
gets(buf,2,stdin); //<----why won't a 1 instead of 2 work here?
if (sscanf(buf,"%d",&choice) != 1) {
printf("Please enter a valid selection\n");
printf("Press <ENTER>\n");
getchar();
menu();
}
printf("blah");//if got this far, must be number.
return;