我的程序应该分析输入以查看其标识符。但是,每当我输入一个合法标识符时,它就会说它是非法的。有什么问题吗?
#include <stdio.h>
int main()
{
int legal = 0;
char ch;
printf("enter:");
ch = getchar();
while (ch != "\n") {
if ((ch >= 'a' && ch <= 'z') || (ch>='0' && ch<='9')||(ch>='A' && ch<='Z')||(ch=='_')) {
legal = 1;
}
else{
legal =0;
printf("Illegal");
break;
}
ch = getchar();
}
if (legal == 1) {
printf("legal");
}
}
答案 0 :(得分:3)
请记住,"\n"
和'\n'
是两个完全不同的事物,第一个是char*
,第二个是char
。解决该问题,您的代码将正常工作。
如果启用警告,则会得到以下提示:
getch.cpp:9:15: warning: result of comparison against a string literal is unspecified (use strncmp instead) [-Wstring-compare]
while (ch != "\n") {
^ ~~~~
getch.cpp:9:15: error: comparison between pointer and integer ('int' and 'const char *')
while (ch != "\n") {
~~ ^ ~~~~
1 warning and 1 error generated.
像clang
这样的编译器,-Wall
会警告您类似的简单错误。