Question
In C++ How can I split the cin.fail into its own .cpp and range to its own, thus having 2 .cpp file that stand alone
In C++
How can I split the cin.fail into its own .cpp and range to its own, thus having 2 .cpp file that stand alone by itself? using functions.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include
bool readUserInput(int& input) { int j; bool flag = true; int attempts = 0;
while (flag && (attempts <3)) { cout << " enter an integer between 0 and 100: "; cin >> j; attempts++; // check if the user entered a non integer value if (!cin.fail()) { if (j >= 0 && j <= 100) { cout << "attempts: " << attempts << ": " << j << endl; flag = false; // exit loop} } else cout << " enter a value 0<= x <=100 "; } else { cout << " error reading an int"; cin.clear(); // clears all errors // this is a compund operation: cin.rdbuf()->in_avail() is a method call to the cout object // that returns the numbr of characters in the stream of the input buffer. // cin.ignore(...) flushes from the buffer the number of characters given by its // argument cin.rdbuf()->in_avail(). cin.ignore(cin.rdbuf()->in_avail()); // Note that the reason you have to use ignore is because // the stream extraction operator does not consume the ending // return (nor any whitespaces after it). cout << " error cleared"; } } // end of while loop return !flag; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started