0

I am trying to write a programme that reverses words on each line.

#include <stdio.h>
int main() 
{
    char word[2001], letter;
    int size = 0, i;
    while((letter = fgetc(stdin)) != EOF) 
    {
        word[size] = letter;
        size++;
    }

    for(i = size - 1; i >= 0; i--) 
    {
        printf("%c", word[i]);
    }
    return 0;
}

this code works but it reverses everything I mean for example if I input

Hello
my
friends

the output is:

sdneirf
ym
olleH

But I want an output like this:

olleH
ym
sdneirf

what is the thing I have to fix?

2
  • Read the line into a buffer with fgets Commented May 4, 2020 at 7:40
  • I suppose you would have to look for word delimiters and then reverse the individual words. Commented May 4, 2020 at 7:41

1 Answer 1

2

You should do printing at end of each lines.

Also return value of fgetc() should be stored to int, not char, because the return value is int and converting it to char may be obstacle when compareing with EOF.

fixed example:

#include <stdio.h>
int main() 
{
    char word[2001];
    int size = 0, i;
    for (;;)
    {
        int letter = fgetc(stdin);
        if (letter == '\n' || letter == EOF) {
            for(i = size - 1; i >= 0; i--) 
            {
                printf("%c", word[i]);
            }
            if (size > 0) putchar('\n');
            size = 0;
            if (letter == EOF) break;
        } else {
            word[size] = letter;
            size++;
        }
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, i didn't know about that kind of use of for loop: for(;;).

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.