0

I want a user to enter a char. I want to filter what they enter and take only the first char they type.

int main(){
    while (true){
        char n = readOption();
        cout << n << std::endl;
    }
    return 0;
}


char readOption() {
    char input = '\0';
    while (input != '\n') {
        input = cin.get();
        if (isalpha(input)) {
            break;
        }
    }
    return toupper(input);
}

If I enter 13@ jkjoi, the console prints.

J
K
J
O
I

I only want it to print J. Why is it printing the other letters as well?

Chronicle
  • 1,565
  • 3
  • 22
  • 28

2 Answers2

2

It is printing all of the characters because (after you fix your semi-colon error) you loop forever:

while (true)
{
    char n = readOption();
    cout << n << std::endl;
}

This will call your read function over and over, forever! Your read function loops until he gets an alpha character, so it ignores "13@ " and then grabs 1 character for each iteration of the while (true) loop. If you want it to stop after reading the first alpha character, don't loop:

char n = readOption();
cout << n << std::endl;

Updated

With your comment, you can actually re-write your code entirely:

std::locale loc;
char c = '\0';
do
{
    // get a character with error checking
    while (!(std::cin >> c))
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
} while (!std::isalpha(c, loc));
// ignore the rest of the input
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • How should I write the code then to allow new user input? If I get rid of the loop but just add a new n = readOption(); and a new cout, it won't ask for new user input, instead it behaves just like it does now. – Chronicle Jan 16 '14 at 20:36
  • 2
    @Chronicle I'm not sure I understand what you're trying to do, but if you want to discard the rest of the line and ask the user for new input, add `std::cin.ignore(std::numeric_limits::max(), '\n');` in the `while` loop. – Praetorian Jan 16 '14 at 20:39
  • @Chronicle Are you wanting the user to *just* enter a single alpha-numeric character? Do you want to keep or discard the rest of the input after that character? – Zac Howland Jan 16 '14 at 20:42
  • @ZacHowland I want to discard the rest. What Praetorian said worked, although I am hoping to use something other than numeric_limits. If I can't find anything else, I'll just be using a large number. – Chronicle Jan 16 '14 at 20:46
  • 1
    @Chronicle In that case, there is no reason to use `std::cin.get()`, see the update. – Zac Howland Jan 16 '14 at 20:55
2

Because you asked it to.

You perform this in a loop, forever.

If you only want to do it once, then simply do it once. Remove your loops.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055