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;
}
#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
$
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?
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/