How do you verify if a password contains a digit?

Hi,

right now I'm working on a final project for my comp sci class. Part of the project involves prompting the user to create their own password. I wanted make it a requirement for the first character to be upper case and for the password to include a digit. So far, it looks like I was able to figure out the uppercase part however I cannot figure out how to verify if the password contains a digit or not. Could someone please help me ? Below I have pasted what I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  #include<iostream>
#include<string>
using namespace std;
int main ()
{
    
    string PName;
    
    cout << "Create Password ";
    getline(cin,PName);
    
    
    for (int i = 0; i < PName.length(); i++)
    {
        while (PName[0] != toupper(PName[0]) ||  !(isdigit(PName[i])) )
                {
                    
                    cout << "Invalid Entry. Please Re-enter: ";
                    getline(cin,PName);
                    
                    

                
                }
                
    }
Many options:
std::find_if http://www.cplusplus.com/reference/algorithm/find_if/
PName.end() != std::find_if( PName.begin(), PName.end(), isdigit )

string::find_first_of http://www.cplusplus.com/reference/string/string/find_first_of/
std::string::npos != PName.find_first_of("0123456789")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <string>
#include <cctype>
#include <algorithm>

bool valid_password( const std::string& str )
{
    // must contain at least two characters
    if( str.size() < 2 ) return false ;

    // the first character must be upper case
    if( !std::isupper( str.front() ) ) return false ;

    // one of the other characters must be a decimal digit
    for( std::size_t i = 1 ; i < str.size() ; ++i )
        if( std::isdigit( str[i] ) ) return true ;

    return false ;

    // or: return true if one of the other characters is a decimal digit
    return std::any_of( str.begin()+1, str.end(), []( char c ) { return std::isdigit(c) ; } ) ;
}

std::string get_password()
{
    std::cout << "password: " ;
    std::string pword ;
    std::getline( std::cin, pword ) ;

    if( valid_password(pword) ) return pword ;

    std::cout << "invalid entry. try again.\n" ;
    return get_password() ;
}
Works perfectly. Thank you guys for all your help. Much appreciated.
Last edited on
Topic archived. No new replies allowed.