C++ examples for File Stream:cin
Input checking with English Measure class
#include <iostream> #include <string> #include <cstdlib> //for atoi(), atof() using namespace std; int isFeet(string); //declaration class Measure//from ww w.ja v a 2s.co m { private: int feet; float inches; public: Measure() { feet = 0; inches = 0.0; } Measure(int ft, float in) { feet = ft; inches = in; } void showdist() { cout << feet << "\'-" << inches << '\"'; } void getdist(); //get length from user }; void Measure::getdist() //get length from user { string instr; while(true) //cycle until feet are right { cout << "\n\nEnter feet: "; cin.unsetf(ios::skipws); //do not skip white space cin >> instr; //get feet as a string if( isFeet(instr) ) //is it a correct feet value? { //yes cin.ignore(10, '\n'); //eat chars, including newline feet = atoi( instr.c_str() ); //convert to integer break; } //no, not an integer cin.ignore(10, '\n'); //eat chars, including newline cout << "Feet must be an integer less than 1000\n"; } while(true) //cycle until inches are right { cout << "Enter inches: "; cin.unsetf(ios::skipws); //do not skip white space cin >> inches; //get inches (type float) if(inches>=12.0 || inches<0.0) { cout << "Inches must be between 0.0 and 11.99\n"; cin.clear(ios::failbit); //"artificially" set fail bit } if( cin.good() ) //check for cin failure { //(most commonly a non-digit) cin.ignore(10, '\n'); //eat the newline break; //input is OK, exit 'while' } cin.clear(); //error; clear the error state cin.ignore(10, '\n'); //eat chars, including newline cout << "Incorrect inches input\n"; //start again } } int isFeet(string str) { int slen = str.size(); //get length if(slen==0 || slen > 5) //if no input, or too long return 0; //not an int for(int j=0; j<slen; j++) //check each character //if not digit or minus if( (str[j] < '0' || str[j] > '9') && str[j] != '-' ) return 0; //string is not correct feet double n = atof( str.c_str() ); //convert to double if( n<-999.0 || n>999.0 ) //is it out of range? return 0; //if so, not correct feet return 1; //it is correct feet } int main() { Measure d; char ans; do { d.getdist(); cout << "\nMeasure = "; d.showdist(); cout << "\nDo another (y/n)? "; cin >> ans; cin.ignore(10, '\n'); //eat chars, including newline } while(ans != 'n'); //cycle until 'n' return 0; }