C Strcmp Fails to Compare with Space

I try to see if formula[i] is a space and if it is number should be zero. But apparently it fails to compare them :S I'm new to C, so does somebody know the problem?

Note: this is not my whole code but only the essential part to understand the problem.

char formula[50] = "1 4 + 74 /";
int number = 0;

for (int i = 0; i != strlen(formula); i++)
{
    if(!isdigit(formula[i]))
    {
      if (strcmp(&formula[i], " ") == 0)
      {
         number = 0; 
      }
    }
}
1

4 Answers

It fails because the string " 4 + 74 /" is not equal to the string " ".

I think what you actually want to compare here are characters, which is as simple as

if (formula[i] == ' ')
{
    // ...
}

For completeness sake, there is a way to perform a string comparison on a prefix of two strings, with the function strncmp, where you can specify how many characters of a string to match.

if (strncmp(&formula[i], " ", 1))
{
    // ...
}

which would be equivalent to the caracter comparison above.

1

That is because they're not equal.

When you do &formula[i], you get a pointer to the character at location i. The string, viewed from that location, continues until the terminating '\0'-character, i.e. that's not a 1-character string.

Just do a direct comparison:

if(formula[i] == ' ')

strcmp compares two strings(two const char*s ending with a \0) and not two characters. In your case,use

if(formula[i]==' ')

The &formula[i] gives you a pointer to where i is allocated.

To tackle the problem , you have to do the following:

if (formula[i] == ' ')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest