0

The specific question is this: the user enters the text, for example, if the user enters

hello (spaces) (spaces) world

The output that the user gets is

hello (space) world.

The following is my code, the adjustment of the number of spaces can be achieved, I am a bit confused because my output will eat the first letter. I want to know why this will happen.

The code:

#include <stdio.h>

int main() {

    int characters = 0;
    while ((characters = getchar()) != EOF) {

        if (characters != ' ') {
            putchar(characters);
        }

        if (characters == ' ') {
            while ((characters = getchar()) == ' ');
            putchar(' ');
        }

    }
}

The output:

Hello  world  world  world
Hello orld orld orld

enter image description here

3
  • 2
    Please include the output in the question (copy-and-pasted if possible) as text, formatted as code (use the {} button). Images of text are discouraged. Commented Dec 19, 2018 at 4:02
  • 1
    Please post console output as code formatted text, not images Commented Dec 19, 2018 at 4:02
  • Sorry, it's the first time I use stackoverflow, I will pay attention to it next time. Commented Dec 19, 2018 at 4:09

1 Answer 1

2
    if (characters == ' '){
        while ((characters = getchar()) == ' ');
        putchar(' ');
    }

This code will keep eating characters until it eats a non-space. But you don't want to eat any non-spaces. A simple fix:

    if (characters == ' '){
        while ((characters = getchar()) == ' ');
        putchar(' ');
        putchar(characters);
    }

Now you eat characters until you eat a non-space, then you output one space, then you output the non-space character you ate.

Sign up to request clarification or add additional context in comments.

2 Comments

You also need to check for EOF here. Probably don't want to print that.
May also want an else break; after that check on EOF to prevent calling getchar() again on a stream with EOF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.