Error check - only alphabeticel inuputs

Hi guys!

How can i set up an error check so only letters are entered? I know how to do it for numbers but have no idea how to make it so it only allows a-z inputs.

Thanks for your help.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cctype>

int main()
{
    char ch ;
    // std::isalpha(ch) : is character ch an alphabetic character?
    // !std::isalpha(ch) : is character ch something other than an alphabetic character?
    // http://en.cppreference.com/w/cpp/string/byte/isalpha
    while( std::cout << "[a-z]? " && std::cin >> ch && !std::isalpha(ch) )
    {
        std::cout << "please enter an alphabetic character\n" ;
    }

    // http://en.cppreference.com/w/cpp/string/byte/tolower
    ch = std::tolower(ch) ; // convert to lower case

    std::cout << "the character entered (in lower case) is: " << ch << '\n' ;
}
Thanks for the snippet of code. Adapted to for my use and it works great. Thanks.

On a side note how could i apply tolower to an array. I haven't a clue how to do this. I tried yesterday but was unsuccessful.

Would you be able to help me here please? http://www.cplusplus.com/forum/general/153088/
> On a side note how could i apply tolower to an array.

Consider using std::string instead of an array. http://www.mochima.com/tutorials/strings.html

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
#include <iostream>
#include <cctype>

int main()
{
    std::string str ; // initially empty
    const std::size_t nchars_needed = 6 ;

    while( str.size() < nchars_needed )
    {
        char ch ;
        while( std::cout << "[a-z]? " && std::cin >> ch && !std::isalpha(ch) )
        {
            std::cout << "please enter an alphabetic character\n" ;
        }
        
        // uncomment this line to convert ch to lower case before appending to the string
        // ch = std::tolower(ch) ; 
                                               
        str += ch ; // append character to string

        std::cout << "the string so far is: " << str << '\n' ;
    }

    for( char& c : str ) // for every char in string str
        c = std::tolower(c) ; // convert it to lower case
    // another option would be to append to the string after converting to lower case
    // if we uncomment line 18, this loop would not be needed.

    std::cout << "the string with characters converted to lower case: " << str << '\n' ;
}

Topic archived. No new replies allowed.