Search code examples
cstrcmp

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; 
      }
    }
}

Solution

  • 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.