Fail State creates problems......why?

In the program below, look at function IF....
If I enter a letter(by mistake), the cin function, go into the failed state(I guess) make the 5 loops, displays the message 5 times, and go out. Whay? because if I enter a negativ number it makes only a loop, and only one message, which is correct.
Thank you in advance!

double a;
for (int i = 1; i <= 5; i++)
{
cin>>a;
if (a < 0 || !cin )
{
cout << "Must a positive number !"<<endl;
continue;
}
cout << sqrt(a) << endl;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cmath>

int main() {
  double a;
  for (int i = 1; i <= 5; i++)
  {
    std::cin >> a;
    std::cin.ignore();
    if (a < 0 || !std::cin ) {
      std::cout << "Must a positive number !" << std::endl;

      // Clear the error flags and go to next new lines for parsing
      if(!std::cin) {
        std::cin.clear();
        std::cin.ignore(256, '\n');
      }
      continue;
    }
    std::cout << std::sqrt(a) << std::endl;
  }
  return 0;
}



$ ./a.out 
4
2
x
Must a positive number !
16
4
b
Must a positive number !
36
6
$ 


consider reading
https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input
Last edited on
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <limits>
#include <cmath>

int main () 
{
    double a{0};
    for (int i = 1; i <= 5; i++)
    {
        while ((std::cout << "Enter a positive number: ")
            && (!(std::cin >> a) || a < 0))
        {
            std::cout << "Must a positive number!\n";
            std::cin.clear ();
            std::cin.ignore (std::numeric_limits<std::streamsize>::max (), '\n');
        }
        
        std::cout << sqrt (a) << '\n';
    }
    return 0;
}
Last edited on
Thank you http://www.cplusplus.com/user/fiji885/ With cin.ingnore () all is ok.
Why? I do not know. You can explain me why? Why is not like a negative number?
Last edited on
closed account (z05DSL3A)
There is a buffer on std::cin, when you enter a letter it can not be 'taken out' of the stream buffer and put into the variable a. You use ignore to take remove the erroneous data from the stream.
http://www.cplusplus.com/reference/istream/istream/ignore/
Thanks for the explanations http://www.cplusplus.com/user/Grey_Wolf/
I appreciate: your program is better and more complete ....
Last edited on
Topic archived. No new replies allowed.