-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintegerValidation.cpp
50 lines (44 loc) · 1.74 KB
/
integerValidation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// Created by Justin Lin on 2019-04-09.
//
/*********************************************************************
** Program name: integerValidation.cpp
** Author: Justin Lin
** Date: 04/09/2019
** Description: This is the implementation file for the a modular
* integer input validation. The function will ask for
* a user input and check to see if it is an integer.
* The input is taken as a string and converted into a
* stringstream object. It then is passed to an integer
* variable using the extraction operator. If it is
* passed successfully to the integer variable and
* there is nothing remaining in the string input,
* the integer will be returned. Otherwise, an error
* message will be printed and the program will loop
* until an integer input is received.
*********************************************************************/
// Adapted from: http://www.cplusplus.com/forum/beginner/170685/#msg851160
#include "integerValidation.hpp"
#include <iostream>
#include <string>
#include <sstream>
using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::stringstream;
int integerValidation() {
string input = "";
int integer = 0;
while (true) {
getline(cin, input);
stringstream convert(input);
// Checks to see if the full string was converted. If there is
// something left in the string input, that means the input is not
// an integer.
if ((convert >> integer) && !(convert >> input)) {
return integer;
}
cout << "Error: Please enter a valid integer." << endl;
}
}