C ++比较char和字符串文字 [英] C++ comparing a char to a string literal
问题描述
这里是初学者...
我正在为我的计算机科学课编写一个非常简单的程序,遇到一个我想知道的问题更多关于。这是我的代码:
I'm writing a very simply program for my computer science class and I ran into an issue that I'd like to know more about. Here is my code:
#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 *')之间的比较。
I'm getting two error messages for my if statement: 1) Result of comparison against a string literal is unspecified (use strncmp instead). 2) Comparison between pointer and integer ('int' and 'const char*').
我似乎已经通过将U括起来解决了这个问题。单引号,或者该程序至少仍然可以运行。但是,正如我所说的,我只是想了解为什么会收到错误消息,以便可以更好地了解自己的工作。
I seem to have resolved the issue by enclosing my U in single quotes, or the program at least works anyway. But, as I stated, I'd simply like to understand why I was getting the error so I can get a better understanding of what I'm doing.
推荐答案
您需要使用单引号代替。
You need to use single quotes instead.
在C语言中,(以及许多其他语言)a 字符常量 是一个单个字符 1 包含在单引号中
In C, (and many other languages) a character constant is a single character1 contained in single quotes:
'U'
而 字符串文字 > 是双引号中包含的任意数量的字符:
While a string literal is any number of characters contained in double quotes:
"U"
您将 courseLevel
声明为单个字符: char courseLevel ;
因此,您只能将其与另一个 char
进行比较。
You declared courseLevel
as a single character: char courseLevel;
So you can only compare that to another single char
.
if(courseLevel == U )
,左侧是 char
,而右侧是 const char *
-指向该字符串文字中第一个 char
的指针。您的编译器告诉您:
When you do if (courseLevel == "U")
, the left side is a char
, while the right side is a const char*
-- a pointer to the first char
in that string literal. Your compiler is telling you this:
指针与整数('
int
'和'const char *
')
因此,您的选择是:
So your options are:
if (courseLevel == 'U') // compare char to char
或者,例如:
if (courseLevel == "U"[0]) // compare char to first char in string
-
完整性提示:您可以具有多字符常量:
int a ='abcd'; //在GCC中为0x61626364
int a = 'abcd'; // 0x61626364 in GCC
但这绝对不是您想要的。
But this is certainly not what you're looking for.
这篇关于C ++比较char和字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!