Baron Baron - 6 months ago 19
C++ Question

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

I need to write a function that will prevent the user to enter any letters, only numbers and it should be 7 digits, the user can't enter less than 7 or more, also the user can't enter number and letters (like 12345ab). How can I do that? Here's the functions that I came up with until this moment:

For the length of the string:

void sizeOfString(string name)
while (name.length() < 7 || name.length() > 7)
cout << "Invalid number of digits\n";
cin >> name;

And this for the letters:

bool containLetters(string test)
if (test.find_first_not_of("abcdefghijklmnopqrstuvwxyz") !=std::string::npos)
return true;
return false;

But it's not really working. What do you guys suggest?


use the isalpha() function.

bool isvalid(string string1){
    bool isValid = true;
    double len = string1.length();
    for (int i=0;i<len;i++){
            isValid = false;

    if(len != 7){
        isValid = false;

    return isValid;

then test

cout << isvalid("1234567"); //good
cout << isvalid("1s34567"); //bad