使用“cin”对象的问题

时间:2011-12-06 17:12:06

标签: c++

在我的最终项目中,一个扑克和黑色杰克模拟器,我的主要功能似乎不想要“cin”工作。整个项目没有语法错误,所以这不是问题,但为了测试它是否运行,我需要“cin”才能工作。以下是我的主要功能,我似乎遇到了麻烦:

#include <iostream>

using namespace std;

#include "card.h"

#include "poker.h"

#include "blackJack.h"





void handlePoker(int&);

void handleBlackJack(int&);

//TO DO:

//FIX CIN PROBLEM

//*pulls hair out*





//main function:

//asks the user what game they want to play

//then calls a function for the appropriate

//game chosen

int main()

{   //two choices:

    //one for quitting the program

    //the other for whichever game they want

    char yesOrNo;

char choice;

int totalMoney;

cout<< "please enter a starting amount to bet with"<<endl;

cin>> totalMoney;

do{

    //ask the user which game they want

    cout<<"would you like to play poker or black jack?"<<endl;

    cout<<"input '1' for poker and '0' for blackjack"<<endl;

    cin>>choice;



    if(choice == '1')

    {

        handlePoker(totalMoney);

    }

    else if(choice == '0')

    {

        handleBlackJack(totalMoney);

    }

    else

    {

        cout<<"I'm sorry, the input you entered was invalid"<<endl;

        cout<<"please try again"<<endl;

    }

    cout<<"would you like to try again?"<<endl;

    cout<<"('y' for yes, or 'n' for no)"<<endl<<endl;

    cin>>yesOrNo;

}while(yesOrNo == 'y' || yesOrNo == 'Y');

}

每次我在do while循环中使用“cin”时,它都不会让我输入任何东西。该程序永远不会停止用户输入。 因为它不是,他是该计划的输出:

"please enter a starting amount to bet with"
*user can enter starting amount here, this "cin" works no problem*
"input '1' for poker and '0' for black jack"
"I'm sorry, the input you entered was invalid"
"please try again"
"would you like to try again?"
"('y' for yes, or 'n' for no)

然后程序结束,因为其中没有任何选项具有任何值。 如果被问到我会包含更多代码,但我相信这就是问题所在。 谢谢所有可能帮助我的人!

编辑:程序确实进入了do while循环,所有的消息都打印出来,但程序根本不会让我输入任何数据,它不会停止让我输入数据,它就好像它们不存在一样。

2 个答案:

答案 0 :(得分:4)

通常当我看到cin忽略所有内容并将我置于无限循环中时,当我输入无效输入时会导致这种情况,并且从不清除流状态。即,输入&#34; A&#34;一个数字会做到这一点。这样做的惯用方法就像是

while (! (cin >> totalMoney)) {
    cout<<"I'm sorry, the input you entered was invalid"<<endl;
    cout<<"please try again"<<endl;
    cin.clear(); //important
} 
// totalMoney holds a valid value now

答案 1 :(得分:0)

尝试使用cin.ignore()而不仅仅是cin让进程等待用户输入

cin>>choice;
cin.ignore();

在MSDN上查看this link以获取更多信息