c - 在 if else 中相互比较时,字符如何存储值?

标签 c

我正在创建一个基本上有(y/n)是,否答案的循环,并且我想在 do while 循环内使用 if else 。当使用input == Y时它似乎不接受它,所以我想知道这在 C 中是否可能?或者如果我以错误的方式接近。

我尝试了一个简单的 if input == Y 但这不起作用,然后我尝试了 strcmp这似乎也不起作用。我在strcmp部分原因是我认为我可能接近答案,但我不完全确定我是否理解 char 值发生了什么。

printf("Would you like to print another invoice? Y=yes, N=No\n");
do {
    scanf("%s", &newInvoice);
    if(strcmp(newInvoice, Y)!= 0) {
        main();
    }
    else if(strcmp(newInvoice, N)!= 0) {
        printf("Goodbye!\n");
    }
    else {
        printf("Invalid Entry (it has to be y or n):\n");
    }
} while(strcmp(newInvoice, N)!= 0); 

当我刚刚 input == Y它希望我初始化 Ym 和 N,所以这似乎不是答案。我希望循环重复问题和输入,直到他们说是或否;如果他们输入类似 G 或任何其他字符,则需要再次循环。

最佳答案

考虑以下内容(稍微更改了 abelenky 的代码)。下面的代码确保小写字母被接受,但它可能有点笨拙,并且可能会表现得更优雅一些。

int main()
{
    char newInvoice, buffer;
    do 
    {
        newInvoice = getchar();
        bufferClean(&buffer); //see underneath the code for the explanation.
        if (newInvoice == 'Y' || newInvoice == 'y') 
        {
            printf("you've chosen YES, continue ......\n");
            break; // breaks the loop and continues with the code.
        }
        else if (newInvoice == 'N' || newInvoice == 'n') 
        {
            printf("you've chosen NO, Goodbye!\n");
            return 1; //main returns 1 and ends the program
        }
        else 
        {
            printf("Invalid Entry (it has to be y or n):\n");
        }
    } while(1);

    printf("exited the loop\n");
    return 0;
}

此外,征求用户的意见有点棘手。我建议在使用缓冲区后清除缓冲区,因为它会传递换行符并可能跳过任何进一步的输入提示。 我创建了一个小函数来执行此操作:

void bufferClean(char *buff)
{
    while ((*buff = getchar()) != '\n' && *buff != EOF);
}

只需在 main() 中声明一个没有值的 char 缓冲区,然后在每次想要清除缓冲区时将其传递给函数(我每次都会这么做)在征求用户的意见后)。我是新手,如有错误请指出!

关于c - 在 if else 中相互比较时,字符如何存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564290/

相关文章:

c - 将 char** 传递给函数,不会改变它的值,还是会改变?

c - 使用递归打印出C中所有可能的字符串

c++ - WinHttpDetectAutoProxyConfigUrl 始终失败,错误代码为 12180 (ERROR_WINHTTP_AUTODETECTION_FAILED)

c++ - setuid 创建一个子进程

c - 数组结构、结构数组和内存使用模式

c - 在函数声明多功能程序中混合类型

c++ - 属性比较在tinyxpath中给出错误匹配和不匹配

C:线程 semaphore_wait 与 while 循环

使用 OpenCV 库和 Makefile 的 C 编译程序

c - 如何比较C中的套接字地址?