Search code examples
c++integerchar

how to handle input type integer when we enter character c++


I have simple form and there is input type int. when i enter input birthYear and currentYear with character, the result is 0 and the program end before the input is filled.

char name[100], birthplace[100];
    int birthYear, currentYear, age;
    
    cout << "Name : ";
    cin.getline(name, 100);
    cout << "Birtyear : ";
    cin >> birthYear;
    cin.ignore();
    cout << "Current Year : ";
    cin >> currentYear;
    cin.ignore();
    cout << "Birthplace : ";
    cin.getline(birthplace, 100);

    age = currentYear - birthYear;
    
    cout << "=================" << endl;
    cout << "NAME : " << name << endl;
    cout << "AGE : " << age << endl;
    cout << "BIRTHPLACE : " << birthplace << endl;

i can't change the data type for birthYear and currentYear to string because it will be calculated.

i have try to convert change the data type for birthYear and currentYear to char and then convert it to int but when i enter character more than 1 the program not going well.

what i expect is when i enter character then the variable will set default value or the program show error message.


Solution

  • When extracting an integer from an input stream, operator>> will put the input stream into an error state if the input can't be converted to an integer. You need to check for this state and clear it before you can continue reading from the stream. For example:

    int readInt(const char *prompt) {
        int value;
        do {
            cout << prompt << " : ";
            if (cin >> value) break;
            cout << "Invalid number entered! Try again\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        while (true);
        cin.ignore();
        return value;
    }
    
    ...
    
    char name[100], birthplace[100];
    int birthYear, currentYear, age;
        
    cout << "Name : ";
    cin.getline(name, 100);
    
    birthYear = readInt("Birth Year");
    currentYear = readInt("Current Year");
    
    cout << "Birthplace : ";
    cin.getline(birthplace, 100);
    
    age = currentYear - birthYear;
        
    cout << "=================" << endl;
    cout << "NAME : " << name << endl;
    cout << "AGE : " << age << endl;
    cout << "BIRTHPLACE : " << birthplace << endl;