C ++将字符放入cin for while循环会导致循环在其外部执行[重复]

Posted

技术标签:

【中文标题】C ++将字符放入cin for while循环会导致循环在其外部执行[重复]【英文标题】:C++ Putting a character into a cin for a while loop causes the loop to execute outside of it [duplicate] 【发布时间】:2017-06-27 22:03:42 【问题描述】:

我决定尝试制作一个小游戏。这是一个简单的生存游戏。部分原因是人们通过选择选项来尽可能地生存。我已经尽可能地将游戏从 1000 行缩小到这个最小情况。

在游戏的某个部分,它会问:“一个送礼物的小丑拜访了你。在 0-10 的范围内,你有多想要礼物?”

如果他们回答 0-10,则循环工作正常。如果他们回答一个字符,比如 y 或 n,循环基本上会强制游戏执行,它不再要求玩家输入任何其他选择。

之前的 while 循环有效,只要玩家还活着,它就会继续。这个小丑 while 循环嵌套在其中。我已经将小丑部分的while循环分解到我认为问题所在的地方......并且还包括了完整的代码以防万一它不在里面。

我的目标很简单,就是如果一个角色被放进去,它就不会破坏这个游戏。

main.cpp - 小丑部分

encounterHurt = 0;
randomEncounter = rand() % 8;
cin.ignore(1, '\n');
if (randomEncounter == 1 && clown == true)
    encounterChoice = 1;
    cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
    while (encounterChoice >= 0 && encounterChoice <= 10)
        cin >> encounterChoice;

        encounterFood = (rand() % 3) + encounterChoice / 2;
        encounterWood = (rand() % 3) + encounterChoice / 2;
        encounterMedicine = (rand() % 2);
        encounterBullets = (rand() % 2);

        if (encounterChoice > 0)
            encounterHurt = (rand() % 10) - encounterChoice;

            if (encounterHurt <= 1)
    health--;
    cout << "The crazy clown stabs you, but still provides gifts.";
            
        
        if (encounterFood > 0) 
            cout << "\nYou were provided with " << encounterFood << " food." << endl;
            food += encounterFood;
        
        if (encounterWood > 0) 
            cout << "\nYou were provided with " << encounterWood << " wood." << endl;
            wood += encounterWood;
        
        if (encounterMedicine > 0) 
            cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
            medicine += encounterMedicine;
        
        if (encounterBullets > 0) 
            cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
            bullets += encounterBullets;
        
    encounterChoice = 11;
    

main.cpp - 压缩代码

#include <iostream>
#include <iomanip>
#include <random>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main() 
    srand (time(NULL));
    int randNumber = 0;
    int food = 4;
    int wood = 4;
    int medicine = 2;
    int bullets = 8;
    int money = 25;
    int randomEncounter = 0;
    int hunt = 0;

    bool axe = false;
    int axeTemp = 0;
    int axeBonus = 0;
    int lumberTemp = 0;
    int lumber = 0;

    int findStore = 0;
    int storeChoice = 0;

    bool gun = false;
    int gunSearch;
    int gunTemp;
    int gunBonus = 0;
    int gunFind = 0;
//    int searches;
//    int searchesBonus;

    int farmFind = 0;
    int farmFood = 0;
    int farmSearch = 0;
    bool farm = false;
    string description;

    int foodTemp = 0;
    int woodTemp = 0;
    int medicineTemp = 0;
    int bulletsTemp = 0;
    int moneyTemp = 0;
    int huntTemp = 0;
    int huntSuccess = 0;
    char huntChoice;

    int encounterFood = 0;
    int encounterWood = 0;
    int encounterBullets = 0;
    int encounterMedicine = 0;
    int encounterHurt = 0;
    unsigned int encounterChoice = 0;

    int hurt = 0;
    int health = 3;
    int healthMax = 3;
    int days = 1;

    char action = '0';
    char pause = '1';
    char classChoice;
    char mainChoice;

    bool clown = true;
    int clownHealth = 5;
    char clownChoice;
    int yourShot = 0;
    int clownShot = 0;

    string place;
    //Food 1 per day per person. Can expand to include more people.
    //Fuel 1 per day, takes that much to stay warm even if fewer people
    //Medicine used one per wound
    //Bullets 1 to hunt, though can spend more to increase chance of success.
    //Days how many days that they have survied.
    //Health, everyone starts with three health. Good, okay, bad, dead.
    cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets << " Health: " << health << endl;

    while (health > 0)
        cout << "\nDay: " << days;
        cout << "\nFood: " << food
             << "\nWood: " << wood
             << "\nMedicine: " << medicine
             << "\nBullets: " << bullets
             << "\nHealth: " << health
             << "\nMoney: " << money << endl;

        if (food >= 1)
            food--;
        

        if (wood >= 1)
            wood--;
        

        if (food <= 0)
            health--;
            cout << "Health lost due to lack of food" << endl;
        

        if (health < healthMax && medicine > 0)
            health++;
            medicine--;
            cout << "Health pack used to heal your character\nHealth : " << health << endl;
        


        action = '0';
        cout << "\n1: Find food" << endl;

        cout << "What's your action? ";
        cin >> action;
        cout << endl;

        if (action == '1')
            //
            //Section for random sites to search.
            //
            //
        randNumber = rand() % 4;
        description = "";
    //Maybe + days at the end, and subtract some, so that they eventually run out of places to check.

        if (randNumber >= 0 && randNumber < 2) 
            place = "supermarket";
            foodTemp = (rand() % 4) + 1;
            woodTemp = (rand() % 2) + 0;
            bulletsTemp = (rand() % 2) + 0;
            medicineTemp = (rand() % 2) + 1;
            moneyTemp = (rand() % 5) + 5;
            

        if (randNumber >= 2 && randNumber < 4) 
            place = "boat house";
            foodTemp = (rand() % 2) + 1;
            woodTemp = (rand() % 4) + 1;
            bulletsTemp = (rand() % 2) + 0;
            medicineTemp = (rand() % 2) + 0;
            moneyTemp = (rand() % 3) + 0;
            

    cout << "You have come to the " << place << "." << endl;
    cout << description << endl;
    food += foodTemp;
    wood += woodTemp;
    bullets += bulletsTemp;
    medicine += medicineTemp;
    money += moneyTemp;

    if (foodTemp > 0)
        cout << "You have found " << foodTemp << " food." << endl;
    if (woodTemp > 0)
        cout << "You have found " << woodTemp << " wood." << endl;
    if (medicineTemp > 0)
        cout << "You have found " << medicineTemp << " medicine." << endl;
    if (bulletsTemp > 0)
        cout << "You have found " << bulletsTemp << " bullets." << endl;
    if (moneyTemp > 0)
        cout << "You have found " << moneyTemp << " money." << endl;

    cout << "\nFood: " << food << " Wood: " << wood << " Medicine: " << medicine << " Bullets: " << bullets
         << " Health: " << health << " Money: " << money << endl;

            //End of search rooms.
        

//Random encounter chance to see if they can gain additional items.
        encounterHurt = 0;
        randomEncounter = rand() % 8;
        cin.ignore(1, '\n');
        if (randomEncounter == 1 && clown == true)
            encounterChoice = 1;
            cout << "\n\nYou were visited by a gifting clown. \nOn a scale of 0-10, how badly do you want a gift? ";
            while (encounterChoice >= 0 && encounterChoice <= 10)
    cin >> encounterChoice;

    encounterFood = (rand() % 3) + encounterChoice / 2;
    encounterWood = (rand() % 3) + encounterChoice / 2;
    encounterMedicine = (rand() % 2);
    encounterBullets = (rand() % 2);

    if (encounterChoice > 0)
        encounterHurt = (rand() % 10) - encounterChoice;

        if (encounterHurt <= 1)
            health--;
            cout << "The crazy clown stabs you, but still provides gifts.";
        
    
    if (encounterFood > 0) 
        cout << "\nYou were provided with " << encounterFood << " food." << endl;
        food += encounterFood;
    
    if (encounterWood > 0) 
        cout << "\nYou were provided with " << encounterWood << " wood." << endl;
        wood += encounterWood;
    
    if (encounterMedicine > 0) 
        cout << "\nYou were provided with " << encounterMedicine << " medicine." << endl;
        medicine += encounterMedicine;
    
    if (encounterBullets > 0) 
        cout << "\nYou were provided with " << encounterBullets << " bullets." << endl;
        bullets += encounterBullets;
    
            encounterChoice = 11;
            


//Option to attack clown
//
//
  
        //End of random encounter from the clown.


//Pause mechanic to prevent the game from cycling.
//            pause = 'b';
//            while (pause != 'a')
//                cout << "\nEnter a to continue: ";
//                cin >> pause;
//            

//End of game message
            cout << endl;
            if (days == 100)
    cout << "You have made it to 100 days. You have beaten this game. You can quit now, or try to see how long you'll last." << endl;
            

//Add day at end of while loop.
            days++;
        
    cout << "You have died after " << days << " days" << endl;

【问题讨论】:

这就是我将其专门缩小到导致问题的一个 while 循环作为最小情况的方法。为了达到这一点,我减少了 1000 行。看来 Ben 使用 cin.clear(); 给出了正确的答案;在导致它的 cin 命令之后。 离题:强烈考虑在课程和结构上投入一些时间。它将帮助您模块化您的代码,因此您将来不必砍掉一千行代码的可能性就会降低。 【参考方案1】:

来自another Stack Overflow的问题...

从流中读取时发生错误时,会获取错误标志 设置并且在清除错误标志之前无法再读取。 这就是你得到一个无限循环的原因。

cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

【讨论】:

谢谢,这似乎是正确的答案。

以上是关于C ++将字符放入cin for while循环会导致循环在其外部执行[重复]的主要内容,如果未能解决你的问题,请参考以下文章

python语言如何结尾?

Shell脚本for循环逐行原样输出

C++ While循环不重新分配字符串值

C语言入门,有手就行老铁 循环语句while do while for

C语言入门,有手就行老铁 循环语句while do while for

C语言入门,有手就行老铁 循环语句while do while for