Paul Thomas
Paul Thomas

Reputation: 11

String scanning in c

So here's a weird problem, when:

if( x[j] == x[j++]) then the scanf function works fine, but if I change it into if( x[j] == x[j + 1]) then scanf function for character array gets called infinite number of times.

It happened in two separate IDE ( but gcc compiler). How can two seemingly unrelated statements (a for loop and an if statement) affect each other ?

main( )
{
    char line[10][100], *x; 
    int i, j, sum;

    scanf("%d", &tc);
    for(i = 0; i < tc; i++)
    {
        scanf("%s", line[i]);
    }


    for( i = 0; i < tc; i++)
    {
        j = 0;
        sum = 0;
        x = line[i];

        while( x[j] != '\0' )
            if(x[j] == x[j+1])
                sum++;

        printf("%d\n", sum);
    }

    return 0;
}

Upvotes: 0

Views: 44

Answers (1)

Paul R
Paul R

Reputation: 213049

In this loop:

        while( x[j] != '\0' ) {
            if(x[j] == x[j+1]) {
                sum++;
            }
        }

you are not incrementing j, so it's an infinite loop, repeatedly testing the same two characters at x[0] and x[1].

To fix this, change it to:

        while( x[j] != '\0' ) {
            if(x[j] == x[j+1]) {
                sum++;
            }
            j++; // <<< increment j on each iteration
        }

or make it more succinct with a for loop:

        for (j = 0; x[j] != '\0'; ++j) {
            if (x[j] == x[j+1]) {
                sum++;
            }
        }

Upvotes: 4

Related Questions