Kar
Kar

Reputation: 3

C++ comparing a character

I am having problems with comparing characters.

Comparing a string works:

(strBuffer.compare("false") == 0)

(where strBuffer is of type string)

but

char next = input->peek();
if(next.compare("'")== 0)

(I need to check if next is a single quote)

Error given:

error: request for member 'compare' in 'next', which is of non-class type 'char'

Upvotes: 0

Views: 1070

Answers (5)

rajenpandit
rajenpandit

Reputation: 1361

You can directly compare a character by using the == operator:

if(next == '\'')

Upvotes: 0

Jonas Schäfer
Jonas Schäfer

Reputation: 20738

This is because char is not string.

You have two options:

  1. Easiest: just compare the char:

    if (next == '\'')
    

    Mind the single quotes here, which tell the compiler that you want a single character instead of a string.

  2. Or convert the char to a string:

    std::string next(1, input.peek());
    if (next == "'")
    

    The 1 tells std::string how many of these characters you want to have. You can use == here (and for all comparisons involving std::string¹) instead of the compare method, which is much more readable.

The explanation of the error message: char is a primitive (non-class) type. So trying to access members of char (such as in your case, compare) isn't going to work, because char variables don’t have any members. A char is usually an eight bit wide integer, which happens to be representable in the programming language as an 8 bit character (you can also assign numbers to chars, like char next = 10).


1: It would not work if you used it like this: if ("a" == "b"), this would not do what you expect it to do (unspecified behaviour).

Upvotes: 2

keyser
keyser

Reputation: 19189

A char is a primitive, not an object (string). You can just compare it directly, with single quotes, which are used to denote single characters:

if (next == '\'') { ... }

The backslash is an escape character, which is needed since we are trying to check for the very character we are using as a delimiter.

And, to compare your string you could use the same syntax, but with double quotes:

if (strBuffer == "false") { ... }

Upvotes: 1

Over Killer
Over Killer

Reputation: 513

That should work:

if(next == '\'')
{
   std::cout << "Got it" << std::endl;
}

Upvotes: 1

Andres
Andres

Reputation: 4501

char next = input->peek();

if(next ==  '\'')
{
    //do something
}

you can also do:

if (strBuffer == "false")
{
    //do something
}

Upvotes: 0

Related Questions