OrangeBike
OrangeBike

Reputation: 145

reversing an array in loop in C

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?

Upvotes: 0

Views: 58

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

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;
}

Upvotes: 2

Related Questions