检查字符是否为单引号。C++

use*_*592 5 c++ equals char

我想检查一个字符是否是单引号。这是我的代码。

char mychar;
if (mychar == '\'')  // Is that how we check this char is a single quote?
{
  cout << "here is a quote" << endl;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

您的代码段无效。代替

char mychar;
if(char=='\'')// is that how we check this char is a single quote?
{
  cout<<"here is a quote"<<endl;
}
Run Code Online (Sandbox Code Playgroud)

必须有

char mychar;
if(mychar=='\'')// is that how we check this char is a single quote?
{
  cout<<"here is a quote"<<endl;
}
Run Code Online (Sandbox Code Playgroud)

而且对象mychar必须被初始化。

至于其他,则确实必须使用包含单引号转义符的字符文字。

或者,如果您有一个字符串文字,例如

const char *quote = "'";

那么你可以写成

if( mychar == *quote )
Run Code Online (Sandbox Code Playgroud)

或者

if( mychar == quote[0] )
Run Code Online (Sandbox Code Playgroud)