gpt4 book ai didi

c++ - 如何验证用户将字符串输入到 std::cin 中?

转载 作者:行者123 更新时间:2023-11-28 04:48:41 25 4
gpt4 key购买 nike

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;
}

`

最佳答案

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;
}

关于c++ - 如何验证用户将字符串输入到 std::cin 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48656916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com