[英]How come my program won't recognize another command?
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. 到目前为止,我目前正在编写程序的主要功能(到目前为止的准系统功能),而我只包括了“ end”命令以结束程序。 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. 该命令是adc(添加系数命令),在一个空格之后,您应该添加一个代表系数的整数和另一个空格,另一个整数代表指数。
Example: adc 4 5 Output: 4x^5 示例:adc 4 5输出: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. 您不能使用这样的格式字符串:
strcmp(buf,"adc %d %d")
来测试某种输入。 Your strcmp
will only signal string equality if the use inputs literally: "adc %d %d"
, not adc
followed by two integers. 如果use的字面意义为:
"adc %d %d"
, 而不是 adc
后跟两个整数,则strcmp
仅会发出字符串相等的信号。
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. 您将需要手动解析输入字符串,方法是在空白字符周围进行标记,使用
strcmp
针对第一个标记(例如adc
,然后分别解析数字。
I don't notice any case
statements in your switch
. 我没有注意到您的
switch
任何case
语句。 It looks like you can just remove the switch
, since you're not using choice
anywhere. 好像您只需要卸下
switch
,因为您没有在任何地方使用choice
。
Also, don't use gets
, use fgets
instead. 另外,不要使用
gets
,而应该使用fgets
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.