Itz*_*984 9 c c++ string strcmp
我有以下内容:
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;
}
Run Code Online (Sandbox Code Playgroud)
我得到的警告是int和char之间的比较.
我试着用strcmp做这样的比较(字符串中的第一个char和给定的char):
if (strcmp(str, ")")==0) { stuff }
Run Code Online (Sandbox Code Playgroud)
但即使比较(应该)正确,它也永远不会进入"东西".
我该怎么办?
Imp*_*Imp 18
如果str是C字符串(以空字符结尾的字符数组),str[0]则为char.
请注意,引号的类型很重要!')'是一个字符,")"而是一个字符串(即一个')'字符后跟一个空终止符).
所以,你可以比较两个字符:
str[0] == ')'
Run Code Online (Sandbox Code Playgroud)
或者你可以比较两个字符串
strcmp(str, ")") == 0
Run Code Online (Sandbox Code Playgroud)
自然地,(如果str字符串真的只包含该括号,则第二个起作用).
您正在将字符 ( str[0]) 与const char[N]( "whatever")进行比较。您需要使用单引号,因为双引号表示字符数组,而单引号表示单个字符:
if (str[0] == ')') // or *str == ')'
Run Code Online (Sandbox Code Playgroud)
等等。
The reason why strcmp was failing as well was because, while the string at some time does point to the ), it has more characters beyond that (i.e. is not followed immediately by a '\0') so the string is not equivalent to the string ")" which has one character.