使用cin.get()似乎并没有读到我期待的角色。出了什么问题?

时间:2017-10-17 23:37:24

标签: c++ if-statement switch-statement cin

所以我正在编写这个程序来执行一个基本任务菜单,其中一个是告诉用户输入的字符是大写,小写还是不是字母。

#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;
}

选择2并输入字母(或任何其他字符)后,输出始终为&#34; C不是字母。&#34;
令我感到困惑的是,如果我采用案例2中的内容并将其放在一个单独的程序中,即

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;
}

它完全按照它应该的方式工作,我甚至不需要cin.ignore(),因为出于某种原因它只会在切换时跳过用户输入部分声明。我在这里缺少什么?

1 个答案:

答案 0 :(得分:5)

我建议您在每次初始化之后使用cin>>而不是cin.get()作为cin.get()来获取&#34;抓住&#34;每次按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;
}