string - "Because" to "use"; C++ -


I am trying to create a simple program that accepts doubles and puts them in a vector if the price is not double Checks to see if the value is Q and not "Q"

Here is the code:

  string str = ""; While (str! = "Q") {double n; Cin & gt; & Gt; N; If (cin.fail ()) {cin.clear (); Cin & gt; & Gt; Str; If (str! = "Q") cout & lt; & Lt; "'" & Lt; & Lt; Str & lt; & Lt; "'" & Lt; & Lt; "Invalid input, please try again!" & Lt; & Lt; Endl; } And ve.push_back (n); }   

This seems to work perfectly though some letters (B, E, C, A, etc.) will not be eliminated when trying to output output. For example, when I type because , str output usage

I find it strange that when I change n from a double to int , all the characters See (input = because and str output because ).

Am I missing something? Is not it an acceptable way to check output if it is not double?

Thank you!

When a user enters because , and you call it Cin & gt; & Gt; N tries to do this , by doing this, it fails at some point , and consumes all the characters (except for parse error) . Only after the consumption of these characters, it fails and fails the operation (which you check with cin.fail () ). Note that a floating point number consists of hexadecimal characters, because they can be encoded in hexadecimal notation *.

Reading the number consumes some hex-digits which is a part of the string you want to consume if failing to parse the input as a number ( Details see the questions below.)

Try to read a simple solution first 'q' and only then which fail , read number , And if the is anything to be failed , then the user has entered something unexpected.

You can see the next letter without consumption (so it is still there in case it is used to parse the number from 'q' .

Example:

  if (cin.peek () == 'q') {// actually consume it, if you cin.get ( ); // quit} else if cin (cin> gt; n) {// process input n} Else {// control user error; you can still get the full line from cin}   

*) Two things are weird and can be discussed in comments: Before settling, hexadecimal numbers should start with 0x , so it must fail on the very first non-digit / non-mark character. Second, why int does not even display this behavior? Integers can also be hex encoded, afaik

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? -