It seems that this is a simple thing but after a few hours of searching I did not find anything ...
I have a function that reads an input string from stdin and keeps it safe. The problem is that when I type anything without typing, it clearly shows some junk in input buffer Reads.
In the following examples, what is "Input"? And whatever happens after the same line is what I type as soon as the following line has read the function.
First of all, this happens when I type something in a while. In this situation, the function works exactly the same way.
  Input? ABCD ABCD input? On the other hand, when I write something for the first time, but enter the second time for the second time:    Input? ABCD ABCD input? CD    And this is when I just enter both times:  
  Input? Y input? Y    This happens when I run it again or else 'Y' or '@' is returned, 'Y' is particularly dangerous for obvious reasons.  
 Here's my code:  
  #include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; # Defined STRLEN 128 int main () {char str [STRLEN]; Quick string ("input?", Str); Printf ("% s \ n", str); Quick string ("input?", Str); Printf ("% s \ n", str); Return EXIT_SUCCESS; } Zero prompt string (const char * _prompt, char * _writeTo) {printf ("% s", _prompt); Fgets (_writeTo, STRLEN, stdin); CleanString (_writeTo); Return; } Zero clear string (four * _str) {four tone [STRLEN]; Int i = 0; Int j = 0; While (_st [i] & lt; 32 || _str [i] & gt; 126) i ++; While (_tr [i] & gt; 31 & amp; _de [i] & lt; 127) {temp [j] = _str [i]; I ++; J ++; } I = 0; While (i & lt; j) {_str [i] = Temporary [i]; I ++; } _tr [i] = '\ 0'; Return; }    I have tried various methods (even insecure people) to flush the input buffer (FSEC, Rewind, Efflus). None of this is able to decide.  
 How can I find an empty input so that I can be prompted again instead of this annoying and potentially dangerous behavior?  
  
   clear string     While part (_st [i] & lt; 32 || _str [i] & gt; 126) i ++;    The string is empty when jumps to  \ 0 .   You should add  _str [i]! = '\ 0    do {printf ("% s")     , _prompt); Fgets (_writeTo, STRLEN, stdin); } While (strangel (_writeTo) & lt; 2);    (Compared with two for the reason of '\ n' ) which puts  fgets  at the end of the buffer)   
 
No comments:
Post a Comment