title: c detecting empty input for stdin
body: <p>This seems like it should be a simple thing but after hours of searching I've found nothing...</p>
  
  <p>I've got a function that reads an input string from stdin and sanitizes it. The problem is that when I hit enter without typing anything in, it apparently just reads in some junk from the input buffer.</p>
  
  <p>In the following examples, the prompt is "input?" and everything that occurs after it on the same line is what I type. The line following the prompt echoes what the function has read.</p>
  
  <p>First, here is what happens when I type something in both times. In this case, the function works exactly as intended.</p>
  
  <pre><code>input? abcd
  abcd
  input? efgh
  efgh
  </code></pre>
  
  <p>Second, here is what happens when I type something in the first time, but just hit enter the second time:</p>
  
  <pre><code>input? abcd
  abcd
  input?
  cd
  </code></pre>
  
  <p>And here is what happens when I just hit enter both times:</p>
  
  <pre><code>input?
  y
  input?
  y
  </code></pre>
  
  <p>It happens to return either 'y' or '@' every time when I run it anew. 'y' is particularly dangerous for obvious reasons.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #define STRLEN 128
  
  int main() {
      char str[STRLEN];
      promptString("input?", str);
      printf("%s\n", str);
      promptString("input?", str);
      printf("%s\n", str);
  
      return EXIT_SUCCESS;
  }
  
  void promptString(const char* _prompt, char* _writeTo) {    
      printf("%s ", _prompt);
      fgets(_writeTo, STRLEN, stdin);
      cleanString(_writeTo);
  
      return;
  }
  
  void cleanString(char* _str) {
      char temp[STRLEN];
      int i = 0;
      int j = 0;
  
      while (_str[i] &lt; 32 || _str[i] &gt; 126) 
          i++;
  
      while (_str[i] &gt; 31 &amp;&amp; _str[i] &lt; 127) {
          temp[j] = _str[i];
          i++;
          j++;
      }
  
      i = 0;
      while (i &lt; j) {
          _str[i] = temp[i];
          i++;
      }
      _str[i] = '\0';
  
      return;
  }
  </code></pre>
  
  <p>I've tried various methods (even the unsafe ones) of flushing the input buffer (fseek, rewind, fflush). None of it has fixed this.</p>
  
  <p>How can I detect an empty input so that I can re-prompt, instead of this annoying and potentially dangerous behavior?</p>