Home > Mobile >  CS50 readability error: expected expression in C when using ! operator on a while loop
CS50 readability error: expected expression in C when using ! operator on a while loop

Time:07-02

#include <cs50.h>
#include <stdio.h>

int count_letters (string text);

int main(void)
{
     string text = get_string("Text: ");
     printf("%i\n", count_letters (text));
}

int count_letters (string text)
{
     int i = 0;
     while (text [i] (! = '\0';'!';'?';'.'))
     {
          i  ;
          return I;
     }
}

I get this error:

Pset2/readability/ $ make readability
readability.c:15:25: error: expected expression
     while (text [i] (! = '\0';'!';'?';'.'))
                        ^
1 error generated.
make: *** [<builtin>: readability] Error 1

How do I fix this? Is this expression used correctly on C?: (! = '\0';'!';'?';'.')

Or is there another way to write this condition: make this loop excluding: '\0';'!';'?';'.'

CodePudding user response:

You can't combine multiple comparisons like that. You need to write each comparison separately, and combine them with a logical operator.

int count_letters (string text)
{
     int i = 0;
     while (text [i] ! = '\0' && text[i] != '!' && text[i] != '?' && text[i] != '.')
     {
          i  ;
     }
     return i;
}

Also, return i; should be after the loop, and the variable should be i, not I (C is case-sensitive).

  • Related