简体   繁体   中英

C fgets() to get input until EOF rather than enter twice

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM