Compare between char in string with given char

I have the following:

int findPar(char* str) { int counter=0; while (*str) { if(str[0] == "(") <---- Warning { counter++; } else if (str[0]== ")") <---- Warning { counter--; } if (counter<0) { return 0; } str++; } if (counter!=0) { return 0; } return 1; } 

The warning I get is a comparison between int and char.

I tried to do a comparison (first char in the string with the given char) also using strcmp, like this:

  if (strcmp(str, ")")==0) { stuff } 

but he never enters into the β€œmaterial”, even if the comparison (should) be correct.

How can I do it?

+4
source share
4 answers

If str is a string C (an array of characters with a null character), then str[0] is char.

Please note that the type of quotes matters! ')' is a char, and ")" is a string (i.e. a ')' char followed by a null terminator).

So you can compare two characters:

 str[0] == ')' 

or you can compare two lines

 strcmp(str, ")") == 0 

Naturally, (the second works if the string str really contains only this bracket).

+12
source

You are comparing a character ( str[0] ) with const char[N] ( "whatever" ). You need to use single quotes because double quotes indicate arrays of characters, while single quotes indicate single characters:

 if (str[0] == ')') // or *str == ')' 

Etc.

The reason for strcmp 's failure was that, although the string at some time points to ) , it has more characters outside it (that is, it doesn't immediately follow '\0' ), so the string is not equivalent to the string ")" which has one character.

+4
source

Double quotes " are line separators, so ")" is a pointer to a string literal in if(str[0] == "(") . You want to compare with the character, so you need to use single quotes

 if(str[0] == '(') 
+2
source

You need if (str[0] == ')') , etc. Pay attention to single quotes (apostrophes) for symbolic literals.

+1
source

Source: https://habr.com/ru/post/1411201/


All Articles