C if语句字符串条件

时间:2016-03-11 05:40:22

标签: c string if-statement

我试图让我的小程序不那么繁琐,所以我做了一个选项来重新启动它。如果我将RepeatC更改为一个整数并且状态1为是而0为否则这没有问题,但我似乎无法理解如何利用这个容量中的字符串。它看起来很好但是打印后崩溃了#34;你想重复计算吗? (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;
    }

3 个答案:

答案 0 :(得分:1)

如果您已将RepeatC声明为char,那么您不必使用strcmp()功能。

你可以直接使用

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

在阅读YN表单用户之前,请确保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;
}

答案 1 :(得分:0)

在C中,你不能使用==来比较字符串,而C中没有原始数据类型作为字符串.C中的字符串是一个char数组,末尾附加'\ 0'表示结束串。 所以,你应该使用strcmp来比较一个字符数组。

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

答案 2 :(得分:0)

试试这个:

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