Hi,
i have:

string letter;

cout << ">Please enter a letter: \n>";
        getline(cin, letter);

What i am trying to work out is how to restrict the user for only entering one letter - has to use a string due to being used in a function later which only takes a string .... i know i hate to say this on here but help ( have tried googling) :D

Thanks

Recommended Answers

All 4 Replies

Test whether letter.length() == 1 and while you're at it, check to make sure it's a valid letter using isalpha() from <cctype> (or your own version).

Can you not change the signature of the function to take a char?

You can use getchar as follows

#include <cstdio>
#include <string>
#include <iostream>

int main () {

    char c = getchar (); 
    std::string s(1,c);
    std::cout << "Entered: " << s << std::endl;
    return 0;
}

That will leave the remainder of the input unused so if you intend to read from the stream after that you will need to first clear the input buffer before doing so.

[EDIT]
On second thought, it is probably best not to mix C-style and C++-style streams. You can achieve the same effect with the following snippet:

#include <string>
#include <iostream>

int main () {

    char c = 0;
    std::cin >> c;
    std::string s(1,c);
    std::cout << "Entered: " << s << std::endl;
    return 0;
}

First thing you need to decide is what happens if 2 or more characters are entered? If this is not a concern, just use cin.get() . Keep in mind all the extra characters will be waiting for the next input. That can mess the user input up royally.
If it is a concern and you only want the first character, read the entire line into a temporary string and move the character into the input string.
Third option is jonsca's suggestion.

Thank you all for your reply's
@jonsca - Unfortunately i did not write the function and cannot change it
@L7Sqr - I cannot use String.
@waltp - jonsca method works as i can just return false if more than one input is entered.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.