初学者程序员在这里...
我正在为计算机科学课编写一个非常简单的程序,并且遇到了一个我想了解更多的问题。这是我的代码:
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
char courseLevel;
cout << "Will you be taking graduate or undergraduate level courses (enter 'U'"
" for undergraduate,'G' for graduate.";
cin >> courseLevel;
if (courseLevel == "U")
{
cout << "You selected undergraduate level courses.";
}
return 0;
}
我的 if 语句收到两条错误消息:
1) 与字符串文字的比较结果未指定(使用 strncmp 代替)。
2) 指针和整数的比较('int' 和 'const char*')。
我似乎已经通过将我的 U 用单引号引起来解决了这个问题,或者该程序至少可以工作。但是,正如我所说,我只是想了解为什么会出现错误,这样我就可以更好地理解我正在做的事情。
您需要改用单引号。
In C, (and many other languages) a character constant http://en.wikipedia.org/wiki/C_syntax#Character_constants is a single character1 contained in single quotes:
'U'
While a 字符串字面量 http://en.wikipedia.org/wiki/C_syntax#Strings是双引号中包含的任意数量的字符:
"U"
你宣布courseLevel
作为单个字符:char courseLevel;
所以你只能将其与另一首单曲进行比较char
.
当你这样做时if (courseLevel == "U")
,左边是一个char
,而右侧是const char*
-- a pointer到第一个char
在该字符串文字中。你的编译器告诉你:
指针与整数的比较('int
' and 'const char*
')
所以你的选择是:
if (courseLevel == 'U') // compare char to char
或者,举个例子:
if (courseLevel == "U"[0]) // compare char to first char in string
-
完整性注释:您can have 多字符常量 https://stackoverflow.com/questions/699301/is-int-x-fooo-a-compiler-extension:
int a = 'abcd'; // GCC 中的 0x61626364
但这肯定不是您想要的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)