Reputation: 3
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
Reputation: 1361
You can directly compare a character by using the ==
operator:
if(next == '\'')
Upvotes: 0
Reputation: 20738
This is because char
is not string
.
You have two options:
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.
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
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
Reputation: 513
That should work:
if(next == '\'')
{
std::cout << "Got it" << std::endl;
}
Upvotes: 1
Reputation: 4501
char next = input->peek();
if(next == '\'')
{
//do something
}
you can also do:
if (strBuffer == "false")
{
//do something
}
Upvotes: 0