Created
September 26, 2018 05:03
-
-
Save tjkhara/db72172d77b01b64cf0ad3153a219cdd to your computer and use it in GitHub Desktop.
Validations to check if what is entered is a number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
#include <string> | |
using std::cout; | |
using std::cin; | |
using std::endl; | |
using std::string; | |
string isItANumber(string input="") | |
{ | |
int count = 0; | |
bool runAgain = true; | |
while(runAgain) | |
{ | |
if(count == 0) | |
{ | |
for (int i = 0; i < input.length(); ++i) { | |
if(!(isdigit(input[i]))) | |
{ | |
// Let runAgain stay true | |
cout << "One of the characters is not a digit" << endl; | |
break; | |
} | |
else | |
{ | |
runAgain = false; | |
} | |
} | |
count++; | |
} | |
else | |
{ | |
cout << "Error! Please enter a number: " << endl; | |
// Put the input in input | |
getline(cin, input); | |
// Check again | |
for (int i = 0; i < input.length(); ++i) { | |
if(!(isdigit(input[i]))) | |
{ | |
// Let runAgain stay true | |
break; | |
} | |
else | |
{ | |
runAgain = false; | |
} | |
} | |
} | |
} | |
return input; | |
} | |
int main() { | |
string input; | |
cout << "Please enter a number: " << endl; | |
getline(cin, input); | |
isItANumber(input); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment