我需要编写一个函数来防止用户输入任何字母,只能输入数字,并且它应该是 7 位数字,用户不能输入少于 7 或更多,用户也不能输入数字和字母(如 12345ab)。我怎样才能做到这一点?以下是我到目前为止想出的功能:
对于字符串的长度:
void sizeOfString(string name)
{
while (name.length() < 7 || name.length() > 7)
{
cout << "Invalid number of digits\n";
cin >> name;
}
}
这是字母:
bool containLetters(string test)
{
if (test.find_first_not_of("abcdefghijklmnopqrstuvwxyz") !=std::string::npos)
return true;
else
return false;
}
但它并没有真正起作用。你们有什么建议?
最佳答案
使用 isalpha()
函数。
bool isvalid(string string1){
bool isValid = true;
double len = string1.length();
for (int i=0;i<len;i++){
if(isalpha(string1[i])){
isValid = false;
}
}
if(len != 7){
isValid = false;
}
return isValid;
}
然后测试
cout << isvalid("1234567"); //good
cout << isvalid("1s34567"); //bad
//etc
关于c++ - 在 C++ 中检查字符串的长度和字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39355516/