c++中检查字符串的长度和字母

Checking a string for its length and letters in C++

本文关键字:检查 字符串 c++      更新时间:2023-10-16

我需要写一个函数,将阻止用户输入任何字母,只有数字,它应该是7位,用户不能输入少于7或更多,用户也不能输入数字和字母(如12345ab)。我该怎么做呢?以下是我到目前为止想到的函数:

对于字符串的长度:

void sizeOfString(string name)
{
    while (name.length() < 7 || name.length() > 7)
   {
    cout << "Invalid number of digitsn";
    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