Behavior of scanf() in C++ -


When I put a string, when scanf () expects float? I thought this would be an exception, but I got infinite loop. Why, and how can I control it?

OK, the code is here

  int main () {float f; scanf ("% f", & amp; f); Cout & lt; & Lt; "F =" & lt; & Lt; F & LT; & Lt; Endl; Return 0; }    

scanf is much read as much as possible, but it hit the end of that input is turned off or if the input number of unread items do not match the specification account, and if it is quickly stops the numbers specified in the format string , And whatever input does not match, will still be in input buffer for future reading. Example:

If you have int count = scanf ("% f", & amp; nbsp;) and input "1.23", then Val will be 1.23 , count will be 1 , and the input will be consumed.

If you have int count = scanf ("% f" and "val") and the input is "George", then val will be unchanged, Count will be 0 , and "Python" will still wait on stdin for another reading usage.

You can find out the failure by comparing the count the number of things you were trying to read, and if it is too small, then somehow get cured. Or discard the input and error.

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -