Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c++ - Compare between a char in a string to a 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 comparison between an int and a char.

I tried to do the comparison (first char in the string vs. given char) also with strcmp like this:

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

but it never goes in to 'stuff' even when the comparison (should) be correct.

how should i do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If str is a C string (null-terminated array of chars), then str[0] is a char.

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

So, you may compare two chars:

str[0] == ')'

or you may compare two strings

strcmp(str, ")") == 0

naturally, (the second works if str string really only contains that parenthesis).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...