Home > Blockchain >  how to make cin only accept a single character and int accept only numbers?
how to make cin only accept a single character and int accept only numbers?

Time:07-04

How can I make cin accept only a single letter in char datatypes and numbers only in double/int datatypes.

#include <iostream>
using namespace std;

int main (){
    char opt;
    int num1, num2, sum;
    cout << "A. Addition" << endl << "B. Subtraction" << endl;
    cout << "Enter option: "; cin >> opt;
    //if I put "ab" here, I want to make cin only read the first letter if possible.
    switch(opt){
        case 'A': case 'a':{
            cout << "Enter first number: "; cin >> num1; //accept numbers only
            cout << "Enter second number: "; cin >> num2;//accept numbers only
            sum = num1 num2;
            cout << "The sum is " << sum;
    
            break;
        }
    }
 }

CodePudding user response:

By definition, operator>> reading into a char will read in exactly 1 character, leaving any remaining input in the buffer for subsequent reading. You have to validate the read is successful and the character is what you are expecting before using it.

And likewise, operator>> reading into an int will read in only numbers. You have to validate the read is successful before using the number, and discard any unused input if the read fails to return a valid number.

Try something like this:

#include <iostream>
#include <string>
#include <limits>
using namespace std;

char ReadChar(const char* prompt) {
    string s;
    do {
        cout << prompt << ": ";
        if (!(cin >> s)) throw ...;
        if (s.length() == 1) break;
        //cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input. Enter a single character" << endl;
    }
    while (true);
    return s[0];
}

char ReadInt(const char* prompt) {
    int value;
    do {
        cout << prompt << ": ";
        if (cin >> value) break;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input. Enter a valid number" << endl;
    }
    while (true);
    return value;
}

int main() {
    char opt;
    int num1, num2, result;
    cout << "A. Addition" << endl << "B. Subtraction" << endl;
    opt = ReadChar("Enter option");
    switch (opt) {
        case 'A': case 'a': {
            num1 = ReadInt("Enter first number");
            num2 = ReadInt("Enter second number");
            result = num1   num2;
            cout << "The sum is " << result << endl;
            break;
        }
        case 'B': case 'b': {
            num1 = ReadInt("Enter first number");
            num2 = ReadInt("Enter second number");
            result = num1 - num2;
            cout << "The difference is " << result << endl;
            break;
        }
        default: {
            cout << "Invalid option" << endl;
            break;
        }
    }
}
  • Related