Reputation: 21
students[#]
is an array of structs and students[#].name
is a string in the struct, and I want to make sure that when the user inputs the name that it's verified to be a string of letters.
Can someone tell me a (simple?) way to get that job done?
I have tried the following to no avail.
bool checkString(const char *str)
{
bool isLetters = true;
while (*str != '\0')
{
if (*str < '65' || *str > '122')
{
//checking to see if it's over or below ASCII alpha characters
isLetters = false;
}
if (*str < '97' && *str > '90')
{
// checking to see if it's between capital and
//lowercase alpha char's
isLetters = false;
}
++str;
}
return isLetters;
}
main
{
//...
for (int i = 0; i < numStudents; ++i)
{
valid = true;
do
{
valid = true;
cout << "Enter NAME for student #" << i + 1 << ":" << endl;
cin >> students[i].name;
if (cin.fail() || !checkString(students[i].name.c_str()))
// tried to see if i could convert it to a c-style
//string to check char by char
{
cin.clear();
cin.ignore();
cout << "Please enter a valid input." << endl;
valid = false;
}
} while (!valid);
//...
return 0;
}
`
Upvotes: 0
Views: 95
Reputation: 158
You will have to check if each char is an alphabet by using ascii values.
bool checkString(string stdunt)
{
bool isLetters = true;
for (int i = 0; i < stdunt.length(); i++)
{
if (stdunt[i] < 65 || stdunt[i] > 122)
{ return false; }
if (stdunt[i] < 97 && stdunt[i] > 90)
{ return false; }
}
return isLetters;
}
int main()
{
int numStudents=5;
string students[numStudents];
for (int i = 0; i < numStudents; i++)
{
bool valid = true;
do{
valid = true;
cout << "Enter NAME for student #" << i + 1 << ":" << endl;
cin >> students[i];
// cout <<students[i];
if (cin.fail() || !checkString(students[i]))
{
cin.clear();
cin.ignore();
cout << "Please enter a valid input." << endl;
valid = false;
}
} while (!valid);
}
cout << "Complete";
return 0;
}
`
Upvotes: 0
Reputation: 87959
ASCII codes are integers, don't put them in quotes.
bool checkString(const char *str)
{
bool isLetters = true;
while (*str != '\0')
{
if (*str < 65 || *str > 122)
{
//checking to see if it's over or below ASCII alpha characters
isLetters = false;
}
if (*str < 97 && *str > 90)
{
// checking to see if it's between capital and
//lowercase alpha char's
isLetters = false;
}
++str;
}
return isLetters;
}
You are still doing the hard way though, the function isalpha
is designed for this task
#include <cctype>
bool checkString(const char *str)
{
bool isLetters = true;
while (*str != '\0')
{
if (!isalpha(*str)))
isLetters = false;
++str;
}
return isLetters;
}
Then you could return immediately when you realise it's not a letter, no point carrying on checking
#include <cctype>
bool checkString(const char *str)
{
while (*str != '\0')
{
if (!isalpha(*str)))
return false;
++str;
}
return true;
}
Upvotes: 1