Dannz
Dannz

Reputation: 495

Modify for-counter inside a loop

I'm trying to modify a counter in if loop because one array index number needs to be corresponded by the other in order for me to change the place of it's text, but the space between the strings add 1 to the counter.

for(int i = 0, n = strlen(p); i < n; i++){

    if(isspace(p[i])){
        c1 = x[i-1];
        printf("%c", p[i]);
    }
    if(isalpha(p[i])){
        c1 = x[i];
        c2 = c1-96;
        printf("%c --- %c ---%d\n",p[i],c1, c2);
    }

This is one of the attempts but it made an infinite loop, I've tried different approach like:

    if(isspace(p[i))){
        printf("%c", p[i]);
        i -= 1;
    }

I even tried to see if 'i' counter really changes so i did:

    if(isspace(p[i])){
        printf("%c", p[i]);
        j = i;
        printf("%d\n", j);
        j = j -1;
        printf("%d\n", j);

which really showed that it goes one backwards, but once i make j = i; it flips to an infinity loop.

Upvotes: 2

Views: 805

Answers (3)

donjuedo
donjuedo

Reputation: 2505

The problem is that i is decremented for a space, but then incremented at the end of the loop, pointing still at the same space. So it repeats infinitely.

EDIT:

// Off the top of my head, and untested,
// but you should be able to get the idea.
char* textString = "Test Test";
int sourceLen = strlen( textString );
for ( int srcIndex = 0, int destIndex = 0; srcIndex <= sourceLen ; srcIndex++ )
{
    if ( textString[ srcIndex ] != ' ' )
    {
        textString[ destIndex ] = textString[ srcIndex ]; // copies null terminator, too
        destIndex++;
    }
}

Upvotes: 2

Jay
Jay

Reputation: 9656

After you increment i inside the loop, it will be incremented again by the for construct. You can change the stop condition:

for(int i = 0, n = strlen(p); i >= n; i++) {

This way, if i is increased by more than one in the last iteration, the loop will still terminate.

This is because

for (CMD_1; COND; CMD_2) CMD_4

is equivalent to

CMD_1
if (COND) {
    CMD_4
    CMD_2
}

Upvotes: 1

Pablo Estrada
Pablo Estrada

Reputation: 3452

You can try using a while loop:

while(i < n ){

    if(isspace(p[i])){
        c1 = x[i-1];
        printf("%c", p[i]);
    }
    if(isalpha(p[i])){
        c1 = x[i];
        c2 = c1-96;
        printf("%c --- %c ---%d\n",p[i],c1, c2);
    }
}

and just add to i in whichever if you want it to increase

Upvotes: 0

Related Questions