samedi 3 août 2019

Why is this code printing a random character inbetween the input and output lines?

I'm trying to write a program where the input is reversed and printed in reverse line by line. For the most part, the code actually does just that. The trouble is that for some (most) of my input, I will get a random character or an extra newline in between my input and my output in the console.

For example, I start the program, type "testing" into the console, and get "gnitseT" back after hitting enter. This is what I expect:


Testing

gnitseT


But then when I type "Hello" into the console, it looks like this:


Hello

g (unexpected)

olleH


Or if I type "running" into the console, instead of getting an unexpected "g" in between my input and output lines, I get an extra newline.


Running

newline here

extra newline here (unexpected)

gninnuR


#include <stdio.h>




void reverse(int length, char s[])
{
    int i;

    for (i = length; i >= 0; i--)
    {
        printf("%c", s[i]);
    }
    printf("\n");

}


int main(void)
{
    char smain[2000];
    int c;
    int i;

    i = 0;
    while ((c = getchar()) != EOF)
    {
        smain[i] = c;
        i++;
        if (c == '\n')
        {
            reverse(i, smain);
            i = 0;
        }
    }

    return 0;
}

The expected behavior is for the program to output into the console the reversed input after the enter key is pressed.

Sometimes, especially at the very beginning of the program, it will work perfectly.

Then, it starts giving me a random character in between my input and output, or it starts giving me an extra newline.

I would like to have it so that it just prints the input in reverse order without any unexpected odd characters showing up in between the input and the output.

Thanks for any help.




Aucun commentaire:

Enregistrer un commentaire