theAlphaMelon
theAlphaMelon

Reputation: 17

How to Check if a User Input is More than One Letter and Have it Display Correctly in C++

I'm trying to figure out how to prevent my code from continuing if a user has entered more than 1 character. I tried looking through the forums but I couldn't find the right answers I was looking for.

Basically I'm trying to validate if the user has entered more than 1 character and prompt them to try again if they have.

The user input will also be printed out, and for some reason it prints as a number. Here is a sample of my current code:

        //gets student's last initial. Checks if the input is a 1 letter character
        //has a response if it is not
        bool lastEntry = false;
        while (lastEntry != true){
            cout << "Please enter the initial of your last name: " << endl;
            cin >> lastInitial;

            if (isalpha(lastInitial)) {
                cout << "Last initial has been logged." << endl;
                lastEntry = true;
            } 
            else {
                cout << "That is an invalid choice. Please enter a letter: " << endl;
                cin >> lastInitial;
            }//end if
        }//end while loop

        //prints summary of student's input and displays output
        cout << "Your name initials are: " << toupper(firstInitial) << toupper(lastInitial) << endl;
        cout << "Once swapped, your name initials will be: " << toupper(lastInitial) << toupper(firstInitial) << endl;
    }//end Choice A option

When I test it, the numerical validation works, but when I type more than 1 character for my input, it will finish my code. This is what it shows:

enter image description here

Notes: firstInitial and lastInitial are declared in the beginning of my code as:

char firstInitial;
char lastInitial;

I currently have #include iostream and #include ctype.h and I use //using namespace std;// to remove the usage of std:: in my code. If this has specifically been asked, I apologize; and please send me a link to the answer! If my code could be more efficient, please let me know that as well! Thank you.

Upvotes: 0

Views: 803

Answers (1)

Roya Ghasemzadeh
Roya Ghasemzadeh

Reputation: 691

toupper returns an integer and you need to convert it to a char when printing. Like this :

static_cast<char>(toupper(lastInitial))

Upvotes: 1

Related Questions