Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Validation functions for the course of OOP'2024
- // (c) [email protected]
- // 2025-03-07 first draft
- #include <iostream>
- #include <fstream>
- #include <sstream>
- #include <cctype>
- #include <vector>
- using namespace std;
- // gets valid input (single value per line) from cin
- // msgInput: message to ask for data
- // msgError: additional details after invalid input
- // returns a value of type T
- template <typename T>
- T getValue(const string &msgInput, const string &msgError = ""){
- T x; // value to be returned
- while(1){ // loops until input becomes valid
- cout << msgInput;
- cin >> x; // try to read value
- char c = cin.get(); // and one char after
- if(cin.fail() || (c != '\n'))
- { // if reading failed or additional chars found
- cout << "Bad input! " << msgError << endl;
- cin.clear(); // clear error flags in cin
- cin.ignore(1024, '\n'); // clean input buffer
- } else {
- break; // input is valid
- }
- }
- return x;
- }
- // gets valid input (single value per line) from cin
- // msgInput: message to ask for data
- // msgError: additional details after invalid input
- // returns a value of type T
- template <typename T>
- vector<T> getList(const string &msgInput, const string &msgError = ""){
- vector<T> v; // list to be returned
- while(1){ // this loops until input becomes valid
- string line;
- cout << "Enter a list of numbers: ";
- getline(cin, line); // read the whole line
- stringstream ss; // now process it internally
- ss << line;
- int hasErrors = 0; // is zero for valid input
- while(1){ // process every value in the line
- T x;
- ss >> x;
- if(!ss.fail()){ // if the value is valid
- v.push_back(x); // add it to the list
- } else { // we failed
- if(!ss.eof()) // check the reason why
- hasErrors = 1; // garbage stopped us and not the end
- break; // finish processing current line
- }
- }
- if(hasErrors == 0)
- break; // the line is valid
- else { // there was garbage
- cout << "Bad input!" << msgError << endl;
- v.clear(); // clear error flags in cin
- }
- }
- return v;
- }
- // prints the values in a single line
- template <typename T>
- void printList(vector<T> v){
- for(int i = 0; i < v.size(); i++)
- cout << v[i] << " ";
- cout << endl;
- }
- int main(){
- // compute the sum of two numbers - example on how to use getValue
- int x = getValue<int>("Enter first number: ", "Integer value required.");
- int y = getValue<int>("Enter second number: ", "Integer value required.");
- int z = x + y;
- cout << "The sum is " << z << endl << endl << endl;
- // compute the sum of all values in a list - example of how to use getList
- vector<int> values = getList<int>("Enter the list of integers: ");
- printList<int>(values);
- int sum = 0;
- for(int i = 0; i < values.size(); ++i){
- sum += values[i];
- }
- cout << "The sum is " << sum << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement