使用do while循环编写一个程序,如果键入字符,将要求用户再次键入

时间:2014-07-31 04:07:46

标签: c++

这是一款随机猜谜游戏。游戏秘密号码是从用户输入的最小值到最大值。猜测者要求猜测秘密号码,最后应该询问他们是否想再玩一次。如果猜测器太高或太低,还必须有多种打印输出选项。我是编程新手,这让我很难过。任何帮助,将不胜感激。

现在,我无法让用户在do while循环中输入类型字母后再次使用cin。因此,任何有关最佳途径的建议都将受到赞赏。

cout<<"\nEnter ur amount to play game: ";
cin>> amount;
do{
    cout<<"\n\n"<< name<< ", What is ur betting amount? ";
    cin>> bet_amount;

    if(bet_amount > amount)
    cout << "Your betting amount is more than your current balance!\n";

    else if(!(cin>> bet_amount)){
            cin.clear();
            cin.ignore();
        }

}while(bet_amount > amount || !(cin>> bet_amount));

while(1){
// Read in guess
cout<< "\n\nEnter a guess to bet: ";
cin >> guess;
...

1 个答案:

答案 0 :(得分:0)

尝试以下更改 -

#include <iostream>
#include <limits>
using namespace std;

int main()
{
    int amount,bet_amount;
    string name;

    cout << "Enter your name and betting amount!\n";
    cin >> name >> amount;
    cout << "Your current balance is " << name << " " << amount << endl;
    cout << "\n *** To stop play press CTRL + c *** \n\n";

    while(1){
            cout << "Enter the amount to bet! : ";
            cin >> bet_amount;

            if(bet_amount == 0){
                    cin.clear(); // takes care of resetting the fail bits
                    cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); //removes any wrong input left in the stream
                    cout << "Please enter the numerical value(Amount)!\n";
                    continue;
            }
            if(bet_amount > amount)
                    cout << "Your betting amount is more than current balance!\n";
            else if(bet_amount == amount)
                    cout << "Your betting amount is equal to current balance!\n";
            else
                    cout << "Your betting amount is less than current balance!\n";
    }
    return 0;
}

退出cin.clearcin.ignorecin in while(1)无法在下次扫描用户的输入。

示例输出 -

root@ubuntu:~/c/basics# ./a.out 
Enter your name and betting amount!
ABC
50
Your current balance is ABC 50

 To stop play press CTRL + c  

Enter the amount to bet! : 25
Your betting amount is less than current balance!
Enter the amount to bet! : w
Please enter the numerical value(Amount)!
Enter the amount to bet! : q
Please enter the numerical value(Amount)!
Enter the amount to bet! : 50
Your betting amount is equal to current balance!
Enter the amount to bet! : 75
Your betting amount is more than current balance!
Enter the amount to bet! : ^C // when you press ctrl+c program terminates!