Problem: after choosing operation, supposedly the user would input a string by calling getString()
. But in this case it skips the function where the user input happens and just proceeds calling the function operations.
Anyone has an idea why is this happening?
int main() {
int choose;
char arr[SIZE];
do {
printf("\n\n-----------------------------------\n");
printf("Enter what operation to perform\n");
printf("[1]Ctype Functions\n");
printf("[2]String Functions\n");
printf("-----------------------------------\n\n");
printf("Enter function: ");
scanf("%d", &choose); //choose what operation
char *str = getString(arr); //user input string, also the problem, it skips this part
switch (choose) {
case 1:
printf("\n\n------------------------------------\n");
printf("Function [%d] Selected\n", choose);
printf("------------------------------------\n");
cTypeFunct(str); //calling ctype function operation
getch();
system("cls");
break;
case 2:
printf("\n\n------------------------------------\n");
printf("Function [%d] Selected\n", choose);
printf("------------------------------------\n");
stringFunct(str); //calling string function operation
getch();
system("cls");
break;
}
} while(choose);
return 0;
}
CodePudding user response:
It is unclear what your getString()
function does, but scanf("%d", &choose)
left the rest of the user's input line after the number pending in stdin
. getString()
probably just reads the newline and returns an empty string.
You could flush the pending input prior to calling getString()
with this:
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
Note that you should test the return value of scanf()
to detect invalid or missing input.
You could also write/use a getInt()
function to read an integer and flush the user input line.
Also note that getString(arr);
does not receive the length of the destination array: either SIZE
is hardcoded, which is not good practice, or the function does not check for a maximum length and may cause undefined behavior on overlong user input.
CodePudding user response:
Using scanf function for input:
What do you think would happen if I input 'asdf' or a special character instead of an integer? When you are coding, consider your users foolish, even hostile, that wants to crash your program. Make it robust.
Scanf wasn't defined for getting input, it is supposed to parse input. Have you seen http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html?
You should also check the return value of scanf to make sure the input is valid.
if (scanf("%d", &choose) != 1)
{
fputs("That's not a valid number!\n", stderr);
return EXIT_FAILURE;
}