Geek shadow
Geek shadow

Reputation: 79

While Loop not satisfying conditon

I have written a while loop to run until it find */ . But unfortunately my loop is exiting as soon as it finds a single * itself .

while (str[++i] != '*' && str[++i] !='/' ); 

Any help would be greatly appreciated. Thank You.

Upvotes: 1

Views: 120

Answers (3)

AnthonyLambert
AnthonyLambert

Reputation: 8830

What about using the function:

char *strstr(const char *s1, const char *s2);

Strstr Docs.

char *substr = strstr ( &str[i], "*/" );

I don't know what your bigger picture is but usually parsing is done by breaking up 'keywords' separated by 'white space' into an array of tokens. "*/" would then be one of your tokens. You might find the C function strtok worth checking out.

Upvotes: 2

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

there are several problems with this construct:

while (str[++i] != '*' && str[++i] !='/' );
  • You don't stop if the string ends and no */ is found.
  • The loop will stop if either a * or a / is found.

You can do it like this:

while (str[i]) {
    if (str[i] == '*' && str[i+1] =='/' ) {
        break;
    }
    i++
}

Upvotes: 3

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21223

Looking at your loop condition and at what you expect the code to do, it is clearly wrong. A while loop stops as soon as its condition is false, this means that it will stop when this is true:

!(str[++i] != '*' && str[++i] !='/')

Which is the same as (str[++i] == '*' || str[++i] =='/'). It stops as soon as it hits a * because of short circuit evaluation. Also, the double increment side-effects are quite subtle to handle and can lead to hard to track bugs.

You are also missing the check for end of string. I'd advice to do something like:

while (str[i] != '\0' && !(str[i] == '*' && str[i+1] =='/')) {
    i++;
}

Or, equivalently,

for (; str[i] != '\0' && !(str[i] == '*' && str[i+1] =='/'); i++)
    ; /* Intentionally left blank. */

Upvotes: 6

Related Questions