zeurosis
zeurosis

Reputation: 183

Using cin.get() doesn't seem to read the character I'm expecting. What's wrong?

so I'm working on this program to perform a menu of basic tasks, one of which is to tell whether a character input by the user is uppercase, lowercase, or not a letter.

#include <iostream>
using namespace std;

int main () {

    int mi;

    cout << "1) Area of Circle" << endl;
    cout << "2) Character Detection" << endl;
    cout << "3) Capitalization 1-3-5" << endl;
    cout << "4) Binomial Roots" << endl;
    cout << "0) Quit" << endl;

    cin >> mi;

    switch (mi) {
        case 2:
        {
            char c;
            cout << "input a character:  ";
            cin.get(c);
            cin.ignore(); /////// unsure if using this properly
            if ('a' <= c && c <= 'z') {cout << "c is lower case" << endl;}
            else if ('A' <= c && c <= 'Z') {cout << "C IS UPPER CASE" << endl;}
            else { cout << "C is not a letter" << endl;}
        }
            break;
    }


    return 0;
}

after selecting 2 and inputting a letter (or any other character) the output is always "C is not a letter."
What confuses me is that if I take what's in case 2 and put it in a separate program, i.e.

using namespace std;
int main () {
    char c;
    cout << "input a character:  ";
    cin.get(c);
    if ('a' <= c && 'z' >= c) {cout << "c is lower case" << endl;}
    else if ('A' <= c && c <= 'z') {cout << "C IS UPPER CASE" << endl;}
    else { cout << "C is not a letter" << endl;}
    return 0;
}

It works exactly how it's supposed to, and I don't even need cin.ignore(), because for some reason it only skips the user input part when it's in the switch statement. What am I missing here?

Upvotes: 0

Views: 963

Answers (1)

Shiv Kumar
Shiv Kumar

Reputation: 1114

I would recommend you to use cin>> instead of cin.get() as the cin.get() after every initialization is there to "grab" the newline character that gets put in the stream every time you press enter.

#include <iostream>
using namespace std;

int main () {

int mi;

cout << "1) Area of Circle" << endl;
cout << "2) Character Detection" << endl;
cout << "3) Capitalization 1-3-5" << endl;
cout << "4) Binomial Roots" << endl;
cout << "0) Quit" << endl;

cin >> mi;

switch (mi) {
    case 2:
    {
        char c;
        cout << "input a character:  ";
        cin>>c;
        cin.ignore(); /////// unsure if using this properly
        if ('a' <= c && c <= 'z') {cout << "c is lower case" << endl;}
        else if ('A' <= c && c <= 'Z') {cout << "C IS UPPER CASE" << endl;}
        else { cout << "C is not a letter" << endl;}
    }
        break;
}


return 0;
} 

Upvotes: 5

Related Questions