C++ “使用”的问题;cin";对象
在我的最后一个项目,扑克和黑杰克模拟器中,我的主要功能似乎不希望“cin”工作。整个项目没有语法错误,所以这不是问题,但是为了测试它是否运行,我需要“cin”来工作。以下是我的主要功能,我似乎遇到了问题:C++ “使用”的问题;cin";对象,c++,C++,在我的最后一个项目,扑克和黑杰克模拟器中,我的主要功能似乎不希望“cin”工作。整个项目没有语法错误,所以这不是问题,但是为了测试它是否运行,我需要“cin”来工作。以下是我的主要功能,我似乎遇到了问题: #include <iostream> using namespace std; #include "card.h" #include "poker.h" #include "blackJack.h" void handlePoker(int&); vo
#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.ignore()而不是仅使用cin等待用户输入
cin>>choice;
cin.ignore();
查看MSDN以了解更多信息通常当我看到
cin
忽略所有内容并将我置于无限循环中时,这是由于我输入无效输入而从未清除流状态造成的。也就是说,为一个数字输入“A”就可以了。这样做的惯用方法如下
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
while(!(cin>>totalMoney)){
cout§27.7.2.2.1每个格式化输入函数通过构造一个带有noskipws参数false的sentry类对象开始执行。
§27.5.3.1.2跳过-在某些输入操作之前跳过前导空格。
。如果只使用格式化输入,则不需要忽略空格。
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