Home > Net >  How to make sure input into a char isn't too long?
How to make sure input into a char isn't too long?

Time:11-29

So I'm trying to make sure the user enters only one charcter. Like if the input is "ab", the code will throw an exception.

char ch = ' ';
std::cin >> ch;

// I'm stuck here

CodePudding user response:

You can enter the input into an entire string, and process just the first character:

#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cin >> input;
    char ch = ' ';
    if ( input.size() > 1 )
    {
       // Entered more than 1 character
    }
    else
       ch = input[0];
}
  •  Tags:  
  • c
  • Related