用C语言中的字符串比较来实现if语句

3

我需要写一个简短的C代码,当我输入“random”时,生成一个介于1和6之间的随机数。如果我输入“exit”或“quit”,程序必须结束。虽然“quit”和“exit”起作用,但当我输入“random”时没有任何反应。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    printf("enter your command");
    char input[100];
    fgets(input, 100, stdin);

    if (strcmp(input, "quit") == 0){
       exit(0); 
    } else if (strcmp(input, "exit") == 0) {
       exit(0);
    } else if (strcmp(input, "random") == 0) {
       srand(time(NULL));
       int random_number = rand() %7;
       printf("%d\n",random_number);     
    }
    return 0;
}

一个简单的步骤是在结尾添加 else { printf("Huh? Got [%s]\n", input); },这将显示正在发生的事情。此外,您的 exitquit 比较都不起作用;当它们失败时,程序会静默退出。您可以通过在 quitexit(0) 之前添加 printf("Got quit [%s]\n", input);,以及类似地为 exit 添加来查看。如果您使用调试器运行代码,也可以看到这一点。 - Jonathan Leffler
2个回答

4
你需要移除通过fgets读取的字符串末尾可能附加的换行符'\n'
例如:
char input[100];
input[0] = '\0';

if ( fgets (input, 100, stdin) )
{
    input[strcspn( input, "\n" )] = '\0';
}

请注意,此声明中的初始化程序

int random_number = rand() %7;

生成范围在[0, 6]内的数字。如果需要范围为[1, 6],则初始化应如下:

int random_number = rand() %6 + 1;

根据C标准,没有参数的main函数应该声明为:

int main( void )

3

您的fgets调用正在读取插入的命令以及末尾的换行符。因此,您应该与换行符进行比较,或选择不同的输入读取方法(例如使用scanf,有助于处理任何空格,或自己删除换行符)。

strcmp(input, "quit\n") == 0
strcmp(input, "exit\n") == 0
strcmp(input, "random\n") == 0

在前两个命令中,您可能没有注意到,但它们也未通过测试。

您还可以添加最后一个else来抓取任何未匹配的内容。只需更改那部分(而不处理换行符)就可以证明其他部分也无法匹配:

/* ... */
} else {
    printf("unknown command\n");
}

使用scanf的示例:

char input[101];
scanf(" %100s", input); /* discards any leading whitespace and
                         * places the next non-whitespace sequence
                         * in `input` */

谢谢我的朋友 :) 并且感谢你注意到了我在随机数方面的错误,我确实应该得到1-6之间的随机数。 - JangoCG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接