C if语句字符串条件

标签 c string if-statement

<分区>

我试图让我的小程序测试起来不那么乏味,所以我选择了重新启动它。如果我将 RepeatC 更改为整数并且状态 1 为是,0 为否,那么这没有问题,但我似乎无法理解如何以这种能力使用字符串。就目前而言,它符合要求,但在打印“你想重复计算吗?(Y/N)”后崩溃

理想情况下,我想要一个字符串数组,根据我使用 Python 的经验,您可以只输入字符串 == "字符串 1"、"字符串 2".... 或类似的东西,这已经有一段时间了,但您可以创建数组。

你不能用 C 来做吗?最好的解决方法是什么?

这是我的代码。

LOOP2:                                                                          //LOOP for error handling
    printf("Would you like to repeat the program? (Y/N)\n");        //Input request to restart
    scanf("%c", &RepeatC);                                                          //Scan for input
    if (strcmp(RepeatC, "yes")==0)                                                                  //Restart condition
    {
        goto LOOP1;
    }
    else if (strcmp(RepeatC, "no")==0)                                                              //End program condition
    {
        return 0;
    }
    else                                                                                                    //Error handling condition
    {
        printf("Your input was invalid. Please enter 1 for yes or 0 for no.\n");
        goto LOOP2;
    }

最佳答案

如果你有申报RepeatC作为 char那么你不必使用 strcmp()功能。

可以直接使用

if (RepeatC== 'Y'))  //Restart condition "Y" means 'Y''\0'
{
    goto LOOP1;
}
else if (RepeatC== 'N') //End program condition
{
    return 0;
}
else

在阅读 Y 之前和 N表单用户确保RepeatC不会包含 \0在里面

如果你声明了RepeatC作为字符串,那么您必须使用 %s 读取用户的选择然后你可以使用 strcmp()功能

printf("Would you like to repeat the program? (Y/N)\n");     //Input request to restart
scanf("%s", &RepeatC);                                      //Scan for input
if (strcmp(RepeatC, "Y")==0)                                                                          //Restart condition
{
    goto LOOP1;
}
else if (strcmp(RepeatC, "N")==0)                                                              //End program condition
{
    return 0;
}
else                                                                                                    //Error handling condition
{
    printf("Your input was invalid. Please enter 1 for yes or 0 for no.\n");
    goto LOOP2;
}

关于C if语句字符串条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35933048/

相关文章:

c - 将 Dijkstra 算法修改为 A* 实现

c - 为什么 memcpy 返回的字符串永远不等于数组中存在的相同字符串?

c - 是否可以从 Linux 下的 C 程序中找到屏幕分辨率?

java - java中如何删除子字符串

javascript - 小故障但可能是一个重要问题

c - 将字符串中的单个字符附加到 char 指针上

string - 如何标记两个字符串之间的差异

c++ - 如何从文本文件中取出标记并将其放入二维矩阵中?

python - swift if or/and 语句,如 python

php - 使用 IF 语句加载数据本地 infile