I am currently writing a program’s main function(the bare-bone function so far) so far I’ve only included the “end” command to end the program. Whenever anything else is typed that isn’t a command, it will output an error message. However, now that I’m inputting more commands within the loop, it doesn’t seem to be recognizing anything else. I’m writing a program that creates polynomials after prompting the user to enter coefficients and exponents.
The command is adc(add coefficient command) and after a space you’re supposed to add an integer standing for the coefficient and another space with another integer standing for the exponent.
Example: adc 4 5
Output: 4x^5
int main(void){
char buf[5]; //Creates string array
unsigned int choice;
printf("Command? "); // Prompts user for command
fflush(stdout);
gets(buf); //Scans the input
while(strncmp(buf, "end", 3) != 0) //Loop that goes through each case, so long as the command isn't "end".
{
switch( choice ){
//Where the other cases will inevitably go
if((strcmp(buf,"adc %d %d"))== 0){
}
break;
default:
printf("I'm sorry, but that's not a command.\n"); //Prints error message if input is not recognized command
fflush(stdout);
break;
}
printf("Command? "); //Recycles user prompt
fflush(stdout);
gets(buf);
}
puts("End of Program."); //Message displayed when program ends
}
You can’t use a format string like this:
strcmp(buf,"adc %d %d")to test for a certain kind of input. Yourstrcmpwill only signal string equality if the use inputs literally:"adc %d %d", notadcfollowed by two integers.You’ll need to parse the input string manually, by tokenizing around whitespace characters, checking the first token with
strcmpagainst e.g.adc, then parsing the numbers separately.I don’t notice any
casestatements in yourswitch. It looks like you can just remove theswitch, since you’re not usingchoiceanywhere.Also, don’t use
gets, usefgetsinstead.