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. Your strcmp
will only signal string equality if the use inputs literally: "adc %d %d"
, not adc
followed by two integers.
You'll need to parse the input string manually, by tokenizing around whitespace characters, checking the first token with strcmp
against eg adc
, then parsing the numbers separately.
I don't notice any case
statements in your switch
. It looks like you can just remove the switch
, since you're not using choice
anywhere.
Also, don't use gets
, use fgets
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.