mercredi 18 avril 2018

I can't calculate difference between two characters

Hi guys we got a homework assignment. We have to convert if statements that have "!=" in them to branch zero(==0) or branch positive(>0).

However the code generates weird input when I do that.

Could someone tell me what I am doing wrong?

original code

#include <stdio.h>

int ch, spaces = 0;
int diff;

int main(void) {


while( (ch = getchar()) != EOF) {
    if( ch == ' ') {

        if( ++spaces == 3) {

            putchar('*');

            spaces = 0;
        }

    } 
    if(ch!=' ') {

        for( int i=0; i<spaces; i++) 
        putchar(' ');
        spaces = 0;
        putchar(ch);
    }
}

return 0;
}

edited code:

#include <stdio.h>

int ch, spaces = 0;
int diff;

int main(void) {


while( (ch = getchar()) != EOF) {
    if( ch == ' ') {
        if( ++spaces == 3)
         {
            putchar('*');

            spaces = 0;
        }

    }
     diff = ch-' ';
     if(diff==0) {
        for( int i=0; i<spaces; i++) 
        putchar(' ');
        spaces = 0;
        putchar(ch);
    }
}

return 0;
}

Aucun commentaire:

Enregistrer un commentaire