Question

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?

Was it helpful?

Solution

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');

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top