This question has already been answered:

Noticed the strange behavior of type double.

Question:

There is a code:

double miles; double km; while(true) { cout << "\nEnter distance in miles: "; cin >> miles; if(miles <= 1 && miles > 0) { km = miles * 1.609; cout << "Your " << miles << " mile in kilometers: " << km << endl; } if (miles > 1) { km = miles * 1.609; cout << "Your " << miles << " miles in kilometers: " << km << endl; } if (miles == 0) { cout << "\nOh, no, man. Enter something but 0\n"; } 

Checked all the options if - works as intended. But when I enter a symbol instead of a number, the last condition with zero is satisfied. But this is not the worst. In this case, the inscription Oh, no, man. Enter something but 0 Oh, no, man. Enter something but 0 appears more than once, if you enter exactly 0, but it appears constantly (as if in an infinite loop). That is, the while(true) works, but for some reason, after entering a character, it stops requesting input from the user. What is the reason?

ps: I know that while (true) is a wildly wrong instruction and should be avoided, I just didn’t want to restart the program each time to check the new value.

pss: if you type int instead of double, then the same, apparently, this is not a feature of exactly double. By the way, if you enter a very long number, then the endless loop also begins.

Reported as a duplicate by participants in pavel , andreycha , aleksandr barakin , Denis , cheops 3 Sep '16 at 18:37 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • @pavel thank, fixed, understood. - Muller
  • Regarding character cuts: try calling cout.precision() with the required number of characters. Just keep in mind that the value of float , normalized to 1,... can not be smaller than 1/2 ^ 23. In your case, the maximum accuracy is 1/2 ^ (23 - 4) = 1/524288 = 0.0000019073 (if I do not confuse anything, since 12 is about 2 ^ 4, that is, it takes 4 bits of mantissa). - ߊߚߤߘ

1 answer 1

Actually the main problem with input / output. Fractional numbers should be output via special manipulators. Link to the answer: Output specification double with cout

If you enter not a number (a word, etc.), then cin sets the flag cin.fail and all attempts to read from it will be obviously unsuccessful, you can reset the flag through cin.clear(); But you still need to reset the unread buffer, for this you can do cin.ignore(INT_MAX); But then it depends on you.

  • wrote cin.clear() at the beginning of the loop, but unfortunately the endless loop is repeated again. - Muller
  • @Muller updated - pavel
  • Thanks, is there a function inverse to cin.clear ()? - Muller