How to prompt user input only letters(a-z)?

So I'm making this small program just to practice stuff and I've stumbled upon this problem, how do I have the user enter only letters?

while browsing in this forum I found this lovely piece:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <limits>

int getInt()
{
	int x = 0;
	
	while(!(cin >> x))
    {
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(),'\n');
		cout << "Invalid input. Only letters please: ";
	}
	
	return x;
}


But this function prompts the user to only input integer values.

I was thinking if I could maybe try tweaking with this one so that the user could only enter letters..no luck though.

so how can I have the user input letters only?
Last edited on
I was bored so I whipped this up. Note: assumes your compiler supports C++11 range based for loops (most modern ones do)

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

std::string getLetters()
{
    std::string input;
    bool valid;

    do
    {
        std::getline(std::cin,input);       // get a line of input
        valid = true;                       // assume it's valid
        for(auto& i : input)                // check each character in the input string
        {
            if(!std::isalpha(i))            // is it an alphabetical character?
            {
                valid = false;              // if not, mark it as invalid
                                    // print an error to the user
                std::cout << "Invalid input.  Please input only alphabetical characters." << std::endl;
                break;              // break out of the for() loop, as we have already established the input is invalid
            }
        }
    }while(!valid);     // keep going until we get input that's valid

    return input;       // once we have valid input, return it
}
Brilliant! that isalpha(i) is what I needed. Thanks!

Although one more thing, suppose I want the user to input an object of type char...The thing is, I want the user to input only a single letter, in the sense if the user inputs
bb
, an error message should be printed stating that the user has not entered a single letter.

Given that the object is not of type string but char, I don't think I could have the loop thing going on to check whether or not only one character was entered. So how do I prompt the user to input a single letter?
same idea. Read the whole line in as a string and verify it is what you want:

1
2
3
4
5
6
7
std::string input;

//...

std::getline(std::cin,input);
if( input.length() != 1 )
  // user input less/more than 1 character 
Last edited on
Topic archived. No new replies allowed.