Question

I've got problem with this peace of code, it should change lower case letters into upper case, and turn multiple spaces into one space. So what it does wrong, it somehow cuts off the first letter like when i write "abcdefg" it givess me on the output "BCDEFG".

main(){ 
int z=0,b;  

        while ( (b = getchar() ) != '\n')
        { 
        b=b-32;
            if (b>0)
            { 
                putchar(b);
            }
            else 
            {
                if (z>=2)
                { 
                    putchar(b);
                }
                else
                { 
                    z=z+1;
                    printf(" ");
                }
            }


        }
}
Was it helpful?

Solution

It seems to generate all the letters for me... have you tried tracing it, to find out what it is doing at each step with the characters you entered?

OTHER TIPS

Your empty space handling has some problems.

It seems you will be printing a space in any case(when your getchar returns 0x20).

you can begin with this to eliminate your spaces problem. otherwise do you have a particular problematic input. because I have no "first letter cut" problem.

main(){ 
int z=1,b;  

        while ( (b = getchar() ) != '\n')
        { 
        b=b-32;
            if (b>0)
            { 
                putchar(b);
                z=1;
            }
            else 
            {
                if (z>=2)
                { 
                    putchar(b);
                }
                else
                { 
                    z=z+1;
                    printf(" ");
                }
            }


        }
}

First you should never being using constants like "32" and instead let the system define what the values are. IE: b -= char(' ');

Second, go look at the functions "islower()" and "toupper()" and C will automatically do that for you.

Consider something like this:

include

main () {

    int     flag = 0;
    char    b;

    while ((b=getchar()) != '\n') {
            if (flag && isspace(b))
                    continue;
            putchar(toupper(b));
            if (isspace(b)) {
                    flag = 1;
                    continue;
            }
            flag = 0;
    }
    putchar('\n');

}

Input: "a bc def ghijghg 123 a1b2c3"

Output: "A BC DEF GHIJGHG 123 A1B2C3"

Note: It looks like the text box is eliminating spaces as the input line has lots of blanks in it.

You should always be aware of your boundary conditions. If the input starts will a bunch of spaces it will still print one space. To eliminate all leading spaces, initialize flag = 1. It will also print a final space if the input has trailing spaces. To eliminate those you would need a slightly different solution, one where you print a space after you see a space and another printable character.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top