students[#]
是一个结构数组,students[#].name
是结构中的一个字符串,我想确保当用户输入它被验证为字符串的名称时信件。
有人可以告诉我(简单吗?)完成这项工作的方法吗?
我尝试了以下内容无济于事。
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;
}
`
答案 0 :(得分:1)
ASCII码是整数,不要用引号括起来。
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;
}
你仍然在努力,功能isalpha
是专为此任务而设计的
#include <cctype>
bool checkString(const char *str)
{
bool isLetters = true;
while (*str != '\0')
{
if (!isalpha(*str)))
isLetters = false;
++str;
}
return isLetters;
}
然后当你意识到这不是一封信,没有点进行检查时,你可以马上回来
#include <cctype>
bool checkString(const char *str)
{
while (*str != '\0')
{
if (!isalpha(*str)))
return false;
++str;
}
return true;
}
答案 1 :(得分:0)
您必须使用ascii值检查每个字符是否为字母。
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;
}
`