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

标签 c++ string function numbers string-length

我需要编写一个函数来防止用户输入任何字母,只能输入数字,并且它应该是 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/

相关文章:

c++ - 简单类 C++ 的 2019 错误

c# - 如何在 C# 中处理 HANDLE 返回?

ruby-on-rails - 如何将此 Ruby 字符串转换为数组?

c++ - std::string 的默认容量?

python - 如何使用返回绘图的函数创建 3D 绘图?

c++ - 为 std::map 定义一个使用值而不是键的比较函数

c++ - 禁用 OpenCV VideoWriter 输出

ruby - 将字符串拆分为值数组

function - Rust 中的绝对值函数

function - 编写函数的简单方法,该函数使用不同的给定输入执行不同的步骤