title: Why is this code printing a random character inbetween the input and output lines?
body: <p>I'm trying to write a program (in C) 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.  </p>
  
  <p>For example, I start the program, type "testing" into the console, and get "gnitseT" back after hitting enter. This has happened successfully and is what I expect. It looks like this:</p>
  
  <hr>
  
  <p>Testing</p>
  
  <p>gnitseT</p>
  
  <hr>
  
  <p>But then when I type "Hello" into the console, it looks like this:</p>
  
  <hr>
  
  <p>Hello</p>
  
  <p>g                (unexpected)</p>
  
  <p>olleH </p>
  
  <hr>
  
  <p>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.</p>
  
  <hr>
  
  <p>Running</p>
  
  <p>newline here</p>
  
  <p>extra newline here (unexpected)</p>
  
  <p>gninnuR </p>
  
  <hr>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  
  
  
  void reverse(int length, char s[])
  {
      int i;
  
      for (i = length; i &gt;= 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;
  }
  </code></pre>
  
  <p>The expected behavior is for the program to output into the console the reversed input after the enter key is pressed. </p>
  
  <p>Sometimes, especially at the very beginning of the program, it will work perfectly. </p>
  
  <p>Then, it starts giving me a random character in between my input and output, or it starts giving me an extra newline. </p>
  
  <p>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.</p>
  
  <p>Thanks for any help.</p>