Home > Mobile >  when i use Increment operator after else statment in a while loop its broke the whole program and it
when i use Increment operator after else statment in a while loop its broke the whole program and it

Time:05-18

when i run this code in the terminal i get a blank line that just wait for nothing when i move the "i ;" under the "while(str[i]!='\0')" it works but thats not what i wanted , any help?

int main(){
    printf("hello kiddo");
    char str[20]="hel a awdaw dwa";
    int i=0;
    char *cleanstring;

    while(str[i]!='\0'){
        if(str[i]==' '){
            continue;   
        }
        else{
            printf("%c",str[i]);    
        }
        i  ;
    }

    return 0;
}

i dont know what wrong with this code

CodePudding user response:

In addition to Johnny Mopp's comment, notice the difference when adding the \n to your printf your program needs to flush the character and will not until the end of line, which as he says never happens since the loop gets stuck.

int main(){
printf("hello kiddo");
char str[20]="hel a awdaw dwa";
int i=0;
char *cleanstring;

while(str[i]!='\0'){
    if(str[i]!=' '){
        printf("%c\n",str[i]);    
    }
    i  ;
}

return 0;

}

CodePudding user response:

i solved this problem editing the "if condition" like that

while(str[i]!='\0'){
        if(str[i]==' '){
            continue;   
        }
        else{
            printf("%c",str[i]);    
        }
        i  ;
    }

the code was long for no reason and its better right now but , still wanna know why it didn't work in the first time.

  • Related