1

I'm creating a program that reverses every line of input.

This is my code:

#include <stdio.h>
#include <string.h>

int main()
{
    char c[100];

    while((fgets(c,100,stdin)) != NULL)
    {
        c[strlen(c) - 1] = '\0';
        for(int i=strlen(c); i>=0; i--)
        {
            printf("%c",c[i]);
        }
    }
}

My test input:

abc 123
lorem ipsum
dolor sit amet

I can print the first line reversed just fine:

abc 123
321 cba

But when I start to enter the next line of input, it's next to the reversed input, so the full program run for the test input looks like this:

abc 123
321 cbalorem ipsum
muspi meroldolor sit amet
tema tis rolod

When it should look like this:

abc 123
321 cba
lorem ipsum
muspi merol
dolor sit amet
tema tis rolod

As a workaround, I press Enter again after the output to be able to enter the next line of input on its own line, but I don't understand why I need to do that.

forfun
  • 67
  • 5
  • 1
    A program to `"reverse the reverse"`? Sounds like you just need a print statement. – Matt C Apr 03 '16 at 04:15
  • 1
    After the `for` loop, `printf("\n");`, or else you'll be entering your next line of input on the same line as the reversed input of the first line. –  Apr 03 '16 at 04:23
  • 1
    You should also ensure that `\n` even is in the string. If `fgets` reads any characters at all, it won't return `NULL` unless an error occurs. This means you could read `Hello` instead of `Hello\n`. Since `` won't be in your buffer, what you'll have read is "Hello", and `c[strlen(c) - 1] = 0;` will result in you printing "lleH" instead of "olleH". –  Apr 03 '16 at 04:24
  • 1
    Please don't post text as image. Post it directly in the question with code formatting. – Spikatrix Apr 03 '16 at 04:27

1 Answers1

2

Your code does exactly what it is told to. So if you want a newline character just after the reversed string, use the following just after your for loop:

putchar('\n');

And you need to keep in mind that there is no guarentee that c[strlen(c) - 1] is a newline character. So, check it before replacing it with a '\0':

size_t len = strlen(c);
if(len && c[len - 1] == '\n')
    c[len - 1] = '\0';

Also, if you are stuck with C89, you might as well need to return a value from main. Just add

return 0; /* Usually, 0 indicates success */

at the end of main in order to get rid of the warning:

source_file.c: In function ‘main’:
source_file.c:8:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

Note that return 0; is implicit in C99 and above.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83