我今天开始 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/