C 用特定字母退出程序
我今天开始C编程 我想写一个程序,不断地要求用户提供一个整数作为输入,直到用户通过输入'q'来告诉程序停止 到目前为止,我已经做到了:C 用特定字母退出程序,c,C,我今天开始C编程 我想写一个程序,不断地要求用户提供一个整数作为输入,直到用户通过输入'q'来告诉程序停止 到目前为止,我已经做到了: #include <stdio.h> int main () { int x; while ( x != "q") { printf("Enter the integer: "); x = getchar(); } return 0; } 我不能让这个项目退出 我做错了什么?我相信这只是一个小错误
#include <stdio.h>
int main () {
int x;
while ( x != "q") {
printf("Enter the integer: ");
x = getchar();
}
return 0;
}
我不能让这个项目退出
我做错了什么?我相信这只是一个小错误,而不是
while(x!=“q”)
试试while(x!=“q”)
一个字符常量是用单引号写的:'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.
}
但是,这可能不太好,因为条件现在是反向的,因此更难读取,x
需要在循环之外声明,并且您可能需要对EOF
/q
以外的值进行一些处理,因此无论如何,您都需要一个if
至于双提示-这将发生,因为换行符
'\n'
也是一个读取字符。这是一个简单的逻辑
这就是你所需要的
#include <stdio.h>
int main()
{
int x;
while(x != 'q')
{
printf("Enter the integer: ");
x = getchar();
//clear buffer or do this
getchar(); //this is required to avoid taking newline '\n'
//as the input (i.e. when you hit enter)
}
return 0;
}
#包括
int main()
{
int x;
而(x!=“q”)
{
printf(“输入整数:”);
x=getchar();
//清除缓冲区或执行此操作
getchar();//这是避免使用换行符“\n”所必需的
//作为输入(即当您点击回车键时)
}
返回0;
}
问题应该是
“如何只按特定字母退出程序而不按“回车”?”
注意:我的答案没有回答。我们在C中,因此
x
在第一次时未初始化,而还有:OP,您没有收到编译器的任何警告吗?C编译器必须对此代码发出诊断,例如“警告:指针和整数之间的比较”。应该考虑编译器发出的任何警告作为错误!调用不受欢迎的“while”-循环的同级姐妹“do-while”将避免初始化x
。由于x
是未初始化使用的,因此您可以通过使用“具有自动存储持续时间的对象的值在其不确定时使用”(6.2.4、6.7.9、6.8)来调用未定义的行为,请参阅(将与实际标准的链接放在手边——在接下来的几年中,你需要一次又一次地使用它才能真正精通C语言——你永远也学不到它的全部内容……)虽然几率不是很高-因为x在While循环之前没有初始化,它可能持有'q'
的值,立即中止。它实际上应该是char x='\0';
才是正确的。这个答案是不完整的。
int x;
do {
printf("Enter the integer: ");
x = getchar();
} while (x != EOF && x != 'q');
#include <stdio.h>
int main()
{
int x;
while(x != 'q')
{
printf("Enter the integer: ");
x = getchar();
//clear buffer or do this
getchar(); //this is required to avoid taking newline '\n'
//as the input (i.e. when you hit enter)
}
return 0;
}