c - 使用特定字母退出程序

标签 c

我今天开始 C 编程。

我想编写一个程序,不断要求用户提供一个整数作为输入,直到用户通过输入“q”值告诉程序停止。

到目前为止我已经得到了这个:

#include <stdio.h>

int main () {
   int x;
   while ( x != "q") {
       printf("Enter the integer: ");
       x = getchar(); 
    }
return 0;
}

输出为:

Enter the integer: 1                                                                                    
Enter the integer: Enter the integer: 1 

而且我无法让程序退出。

我做错了什么?

最佳答案

字符常量用单引号编写:'q'"q" 是一个字符串文字 - 一个字符数组,衰减为指向第一个字符的指针特点。因此编译器给出警告

test.c: In function ‘main’:
test.c:5:14: warning: comparison between pointer and integer
    while ( x != "q") {
              ^~

这是正确的代码

#include <stdio.h>

int main (void) {
    // loop forever. Easier to make the condition to exit with if + break

    while (1) {
        printf("Enter the interger: ");

        // declare where it is used, to avoid it being used uninitialized
        int x = getchar();

        // if an error occurs or there are no more input, x equals to EOF.
        // to be correct, the program will need to handle the EOF condition
        // as well. Notice the single quotes around 'q'
        if (x == EOF || x == 'q') {
            break;
        } 
    }
    return 0; // main defaults to return 0 in standard C ever since 1999,
              // so this could have been omitted.
}

或者 do { } while 循环也可以工作:

    int x;
    do {
        printf("Enter the integer: ");
        x = getchar();
    } while (x != EOF && x != 'q');

但是,这可能不太好,因为由于现在条件已反转,因此更难阅读,因此需要在循环外部声明 x 并且您可能确实需要对 EOF/q 以外的值进行一些处理,因此无论如何您都需要 if

<小时/>

至于双重提示 - 会发生这种情况,因为换行符 '\n' 也是一个读取字符。

关于c - 使用特定字母退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51202755/

相关文章:

c - 多个以太网接口(interface) - 如何创建一个单独的网络并从 C 代码访问

c - 从 DNS 响应获取 IP

c - 指向 char 的指针的问题

c - gcc 不生成调试文件

c - 这段代码中的 `.arr`函数是什么?

C、位移位。连续2类

c - 如何让用户输入一个单词进行字符串比较?

c - C语言中n个数相加

c - 卡在有关数组和移动数字的代码上

c - C 中的默认参数和参数提升