gpt4 book ai didi

c++ - 验证数组 C++ 中的输入数据

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

我有这个程序,我从中取出它:https://intcpp.tech-academy.co.uk/input-validation/它工作正常,我做了一些更改,因为我需要程序不断要求用户输入有效输入,所以为什么它在那里有 while 但是在第 4 次输入后它只询问 4 次输入将有效它不管它是否正确,有谁知道我该如何解决这个问题。谢谢

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main () {

cout << "Please enter name:" << endl;
string userName;
getline(cin, userName);

bool rejected = false;

while (rejected == false)
{
for (unsigned int i = 0; i < userName.length() && !rejected; i++)
{

if (isalpha(userName[i]))
continue;

else if (userName[i] == ' ')
continue;

else
{
cout << "Error, Please enter Patient's name again, First Name: ";
getline(cin, userName);
rejected = false;
}

}
rejected = true;
}

system("pause");
return 0;
}

最佳答案

我个人会做类似的事情

bool is_valid_username(std::string const& username)
{
// First trim the string of all leading and trailing white-space
trim(username);

if (username.length() == 0)
return false; // Input was empty or all spaces

return std::all_of(begin(username), end(username), [](char const ch)
{
return std::isalpha(ch) || ch == ' '; // Only letters and spaces are allowed
});
}

std::string get_username()
{
std::string username;

do
{
std::cout << "Please enter username: ";
std::getline(std::cin, username);
} while (!is_valid_username(username));

return username;
}

[关于trim 功能请see this old answer ]

get_username 函数将在输入为空、全为空格或包含非字母或不包含空格的情况下永远继续请求用户名。

Here's a reference for std::all_of .

Here's a reference about lambda expressions .

关于c++ - 验证数组 C++ 中的输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311410/

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