My instructor is requiring us to read data into an int character using cin>>. However, he says we should be able to handle input such as
asdf
We are not allowed to read data into any other type. To my knowledge, reading in data of the improper type while using cin will just yield an infinite loop. Is there a way around this? Thanks.
I'm new to the I/O stream myself. However, cin.good( ) is what you want. It basically checks to see whether the users input is valid or not. If it returns false, the input is bad. Otherwise, true is returned to the calling routine.
#include <string>
#include <iomanip>
usingnamespace std;
int main ()
{
string name;
cout << "Enter your name";
cin >> name;
cout << "Your name is: " name;
system ("pause);
}
#include<ios>
#include<iostream>
usingnamespace std;
int main(){
int quantity=0;
bool flag=false;
do{
cout<<"\n Please enter the quantity to be sold: ";
cin>>quantity;
if(!cin.good()){
cerr<<"\n ERROR: You entered a negative number or a non-numerical character.\n";
flag=true;
cin.sync();
cin.clear();
}else
flag=false;
}while(flag);
}
quantity must be an int and I have to use the << operator. If someone types in "qwkleh;f;q" or any junk, my program shouldn't crash. Right now, if I do that, the program repeats
Please enter the quantity to be sold of that ticket:
ERROR: You entered a negative number or a non-numerical character.
in an infinite loop. It is not allowing the user to input a new response.
I've copied your code into my IDE and made 3 changes:
1) On line 15, I removed this line. Since flag is false already, reassigning it to false won't have an effect.
2) On line 19, I swapped the value with true.
3) On line 20, I added the ! (NOT) operator.
#include<iostream>
int main(){
int quantity=0;
while ((std::cout << "\n Please enter the quantity to be sold: ")
&& !(std::cin >> quantity) || quantity < 0 )
{
std::cout << "\n ERROR: You entered a negative number or a non-numerical character.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "You entered " << quantity <<std::endl;
}
#include <iostream>
usingnamespace std;
int main() {
int quantity = 0;
do {
cout << "\n Please enter the quantity to be sold: " << flush;
cin >> quantity;
if( cin.good() && quantity >= 0 )
break;
cerr << "\n ERROR: You entered a negative number or a non-numerical character.\n";
cin.sync();
cin.clear();
} while(true);
return 0;
}