Pergunta

I was wondering why the code below doesn’t work exactly like the code below it. What the code is supposed to do, is to remove multiple consecutive spaces and just display one space: so 'it works' becomes 'it works'. The first piece of code just keeps it like 'it works'.

Doesn't work

#include <stdio.h>

main(){
    int c;
    int lastspace;

    lastspace = 0;
    while((c = getchar()) != EOF){
        if(c != ' ')
            putchar(c);
            lastspace = 0;
        if(c == ' '){
            if(lastspace == 0){
            lastspace = 1;
            putchar(c);
            }
        }
    }
}

Works

#include <stdio.h>

main(){
    int c
    int lastspace;

    lastspace = 0;
    while((c = getchar()) != EOF){
        if(c != ' ')
            putchar(c);
        if(c == ' '){
            if(lastspace != c){
            lastspace = c;
            putchar(c);
            }
        }
    }
}
Foi útil?

Solução

In your first example

if(c != ' ')
    putchar(c);
    lastspace = 0;

doesn't place {} braces after the if statement so only the immediate following statement is executed conditionally. Changing indentation and adding braces shows that the code is actually

if(c != ' ') {
    putchar(c);
}
lastspace = 0;

This is the reason why some coding standards mandate the use of {} following all control statements.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top