i need to restrict the user from inputting an integer and string when inputting a char. I have a method for an integer i just need to adapt it for a char. Can anyone help me with this.

char getChar()
    {
        char myChar;
        std::cout << "Enter a single char: ";
        while (!(std::cin >> myChar))
        {
            // reset the status of the stream
            std::cin.clear();
            // ignore remaining characters in the stream
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
           // ^^^  This line needs to be changed.
            std::cout << 

           "Enter an *CHAR*: ";
    }
    std::cout << "You entered: " << myChar << std::endl;
    return myChar;
}

char getChar()
{
    char myChar;
    std::cout << "Enter an Char: ";
    while (!(cin >> myChar))
    {
        // reset the status of the stream
        cin.clear();
        // ignore remaining characters in the stream
        cin.ignore(std::numeric_limits<char>::max() << '\n');
        cout << "Enter an *CHAR*: ";
    }
    std::cout << "You entered: " << myChar << std::endl;
    return myChar;
}

I think you need to explain in more detail.
What are you ultimately trying to do?
What is wrong with the two functions?
What is your definition of an invalid input? ... valid input?

i need to restrict the user from inputting an integer and string when inputting a char.

Read the input into a string. Verify that the string consists of precisely one non-digit character.

char get_single_nondigit_char()
{
    std::string input ;
    while( std::cout << "enter a single non-digit, non-whitespace char: "
            && std::cin >> input
            && ( input.size() != 1 || std::isdigit(input[0]) ) ) ;
    return input[0] ;
}

Well you could do it like this:

#include <cstdio>
#include <iostream>
using namespace std;

int main(){
    cout<<"\\\\: ";
    char c;
    cin.get(c);
    cin.ignore();
    if (c!=' ' && !isdigit(c)){
        cout<<"Ok: "<<c<<".\n";
    }
    else cout<<"Not ok.\n";
    return (0);
}

cin.get(c) will put just the first character from the input stream, even if you type in an entire sentence.

This article has been dead for over six months. Start a new discussion instead.