String over Character data type when validating

How can I use a character in input validation and make it so that it doesn't accept anything other than the valid input.

For example:
I prompt the user...
Continue [Y/N]:
If the user types Ndskjhsfkj (garbage) then the character N will match the one I'm looking for in the validation and take it as N which will exit the loop the prompt is in.

I know I can use a string and fix the problem. Is there another way, except from using a string instead of a char so that I can make it to not accept an answer like Ndskjhsfkj ?

If that's the case and it can only be solved by using a string, Is it a good programming practice to use a string over a char if the input you are validating is just a character?

In this occasion I used "N" instead of 'N'.
I'm surprised nobody has answered this yet, it's a pretty simple one. You will need to include <iomanip> and use the std::setw() function.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <iomanip>

int main()
{
        char Input;
        std::cout << "Type in what you want: ";
        std::cin >> setw(1) >> Input; // Grabs only 1 character
        std::cout << "You chose " << Input << '\n';
        return 0;
}
Megatron 0 thanks for the reply!

However, i'm interested in input validation and not outputting 1 character of the user's input.

If I use char in an input validation when the user types as input some letters where the first letter matches the character of my input validation it takes it as if the user had typed the valid answer.

1
2
3
4
cout << "Continue? [Y/N]: ";
     cin >> answer;
     cin.ignore(1000, 10);
     answer = toupper(answer);

answer is a char variable

if the user types in Yfkjsfhksfhkfs where letter Y is the first letter of what the user had typed it will take the first character as if he had only typed Y. How can I avoid using a string and make character data type look only for Y and not accept answers that contain as their first letter Yksfhsdgjhl.
Last edited on
the example you provided still uses strings if i'm not mistaken..
Topic archived. No new replies allowed.