I'm at a complete loss and don't really know where to begin.
But basically what I need to do is get a 4digit positive integer and filter out incorrect inputs.
Examples of correct inputs: 1234, 0000, etc.
Examples of incorrect inputs: 12, 12wf, etc.
Pseudo-code of what I'm trying to do:
Get the input and put it into an array.
Check the array to see if it's 4 characters long, if it's not display an error and get the input again.
Check the array to see if all 4 values stored are 0-9, if they aren't display an error and get the input again.
#include<iostream>
#include<cctype>
usingnamespace std;
bool doAgain();
int main()
{
while(doAgain());
cout << "Valid input.\n";
return 0;
}
bool doAgain()
{
char a[4];
cout << "Enter a 4 digit number: " ;
for(int i=0;i<4;i++)
{
cin >> a[i];
if(!isdigit(a[i])) // checks if character by character is a digit or not.
{
cout << "Inputs contains non integer char.\n";
cin.ignore(); //ignores the rest of the input.
return 1;
}
}
char x = cin.get();
if(x!='\n') // if you find 1 more char available for input and that character is not the enter button.
{
cout << "Input contains more than 4 characters.\n";
cin.ignore(); //ignores the rest of the characters in the input stream.
return 1;
}
return 0;
}
The only difference between a character array and a string is that a string is a defined class with functions handling the use of the character array. http://www.cplusplus.com/reference/string/string/
lol i just find that character arrays are more useful if you need access to the individual characters of the string, which if youre getting user input you usually are...?