Cin不是在等待输入

Mur*_*ira 1 c++ cin

这是该计划:

#include <iostream>
#include <string>
#include <stdlib.h>


using namespace std;

int main(){


string strKingdom = "";
bool conquered_me;//see if was conquered, was going to use this on other program and true = game over.
int gold;
int food;
int citizens;
int soldiers;



cout << endl <<"Name of kingdom: ";
cin >> strKingdom;
cout << endl << "were you conquered (true/false): ";
cin >> conquered_me;
cout << endl << "How many gold do you have?:";
cin>>gold;
cout << endl << "How many food do you have?:";
cin >> food;
cout << endl << "How many citizens do you have?:";
cin >> citizens;
cout << endl << "How many soldiers do you have?:";
cin >> soldiers;


return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我编译它时,progam只允许我插入前两个变量,然后它显示其余的问题(编译后):

王国的名字:史蒂夫

你被征服了(真/假):是的

你有多少金币?:你有多少食物?:你有多少公民?:你有多少士兵?:

nsi*_*t22 7

bool变量中输入字符串"true" 不起作用.你应该输入10.你的"真实"不能被"消耗",所以它留在缓冲区中.接下来,您正在尝试读取int值,因此"true"也不匹配.等等......直到程序结束.

我就是那样做的:

#include <string>
#include <iostream>

#include <errno.h>
#include <stdlib.h>

using namespace std;

void askForString(string aPrompt, string &aValue) {
    cout << aPrompt << " ";
    cin >> aValue;
}

void askForBool(string aPrompt, bool &aValue) {
    string tString;
    while (1) {
        cout << aPrompt << " ";
        cin >> tString;
        if (tString == "true") {
            aValue = true;
            break;
        } else if (tString == "false") {
            aValue = false;
            break;
        } else {
            cout << "Repeat, please?" << endl;
        }
    }
}

void askForInt(string aPrompt, int &aValue) {
    string tString;
    char *endptr;
    while (1) {
        cout << aPrompt << " ";
        cin >> tString;
        errno = 0;
        aValue = strtol(tString.c_str(), &endptr, 10);
        if (errno || tString.c_str() == endptr || (endptr != NULL && *endptr != 0)) {
            cout << "Repeat, please?" << endl;
        } else {
            break;
        }
    }
}

int main(void) {
    string strKingdom;
    bool conquered_me;
    int gold;
    int food;
    int citizens;
    int soldiers;

    askForString("Name of kingdom:", strKingdom);

    askForBool("were you conquered (true/false):", conquered_me);

    askForInt("How many gold do you have?:", gold);

    askForInt("How many food do you have?:", food);

    askForInt("How many citizens do you have?:", citizens);

    askForInt("How many soldiers do you have?:", soldiers);

    cout << "Kingdom: " << strKingdom << endl;
    cout << "Conquered: " << (conquered_me ? "true" : "false") << endl;
    cout << "Gold: " << gold << endl;
    cout << "Food: " << food << endl;
    cout << "Citizens: " << citizens << endl;
    cout << "Soldiers: " << soldiers << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)