c ++ std :: cin被忽略(缓冲区?)

时间:2016-03-23 21:15:28

标签: c++ buffer cin

有几个与此类似的问题,但它们涵盖了cin的另一种用法。

#include <iostream>

int main(int argc, char *argv[]) {

int coke = 1, sprite = 2, water = 3, fanta = 4, sevenup = 5, choice;

while (true){
    system("cls");
    std::cout << "Choose your drink:\n1) Coke\n2) Sprite\n3) Water\n4) Fanta\n5) SevenUp\n\n";

    std::cin >> choice;

    switch (choice){
    case 1:
        std::cout << "You chose a Coke.";
        break;
    case 2:
        std::cout << "You chose a Sprite.";
        break;
    case 3:
        std::cout << "You chose a Water.";
        break;
    case 4:
        std::cout << "You chose a Fanta.";
        break;
    case 5:
        std::cout << "You chose a SevenUp.";
        break;
    default:
        std::cout << "No choice like that. Here's your money back.";
        break;
    }

    while (true){
        std::cout << "Would you like to buy another beverage? (y/n)";
        char answer1;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        //***********************************************
        //THIS IS WHERE IT HAPPENS
        std::cin >> answer1;
        //THIS IS WHERE IT HAPPENS
        //***********************************************
        if (answer1 == 'y'){
            break;
        }
        if (answer1 == 'n'){
            //end game
            return 0;
        }
    }
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
return 0;

}

我评论了失败的位置&#34;在上面的代码中。该程序要求用户输入1-5。如果输入大于5,则它请求另一个输入。但是,如果用户输入一个字母,而不是一个数字。 &#34;失败的位置&#34;简单地跳过并执行循环而不请求其他输入。

0 个答案:

没有答案