Code: |
#include <stdio.h>
#include <stdlib.h> int i, j, k, m; float jake; char cake[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; char fname[101]; int main(int argc, char *argv[]) { printf("Select an option: \n"); printf("-----------------\n"); printf("1.) Recite the name you entered:\n"); printf("2.) Recite the alphabet\n\n"); scanf("%i", &k); if ( k == 1 ){ printf("Please enter a name: \n"); fgets(fname, sizeof(fname), stdin); printf("The name you entered is: \n"); m = strlen(fname); for ( i = 0; i < m; i++){ printf("%c", fname[i]); } } else if ( k == 2 ){ printf("You want to see the Alphabet?, here you go....\n\n"); for ( i = 0 ; i < 26; i++){ for ( j = 0; j < 250000000; j++); printf("%c \n", cake[i]); } printf("\n"); printf("That is it.\n"); } else if ( k != 1 && k != 2){ printf("Since you gave a response that I do not understand, I cannot give you anything!\n\n"); } system("PAUSE"); return 0; } |
I wrote: |
scanf takes input by matching it against the format string. Think of it as an input parser, since that's what it is. It matches the input against the format string, and quits when it's matched everything it was asked for (in your case, 1 character), or when the input differs from what it's expecting. If you tell it to match "%c54%c" it's going to expect to read one character, followed by 54, followed by another character. If it finds anything else, it bails out.
Note that it won't work if you do scanf("%c\n", &choice); (which would seem like the obvious choice). This would be telling scanf to read 1 character, followed by any amount of whitespace. Since scanf keeps reading from the input until it's matched everything it was asked to match, it will not stop when the user presses Enter (since Enter falls under "any amount of whitespace"). It will only stop when it finds something other than whitespace, after that first Enter. scanf can be a complicated beast for the novice, as it's not entirely intuitive. You may find it simpler to use a function such as fgets (which reads a whole line of input) and do the processing yourself. You could process the string with sscanf, or just compare it to your allowed choices with strcmp(line, "y\n"). Do NOT, however, under any circumstance, use gets: that function is a broken design which you should never use in a real program. You cannot use gets in a secure way (search the web for "buffer overflows" and gets if you're curious), so don't get used to it in the first place. |
output generated using printer-friendly topic mod, All times are GMT + 2 Hours