【发布时间】:2015-07-21 20:37:21
【问题描述】:
这是程序:
#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;
}
问题是,当我编译它时,程序只允许我插入前 2 个变量,然后它会显示其余的问题(编译后):
王国名称:史蒂夫
你被征服了吗(真/假):假
你有多少金币?: 你有多少食物?: 你有多少公民?: 你有多少士兵?:
【问题讨论】:
-
您给出的确切输入是什么?我猜它正在读取您作为“6”值给出的“2”输入。 (您的王国名称中是否有空格?看看:cplusplus.com/reference/string/string/getline
-
只是不要使用
istream::operator>>。很难正确使用。要获取用户输入,请使用std::getline()并解析结果字符串。 -
所以存储 std::string 是唯一有效的方法。接下来的数据类型,包括那个 bool,导致了你的失控行为。这是给你的线索。 :-)
-
just don't use istream::operator>>.这是一个非常愚蠢的建议。新手应该首先学习如何使用标准流,因为它是一个非常基本的接口,基本上可以在任何地方使用。一旦你了解了它的工作原理,你就可以对是否使用它有意见。 -
@sbabbi 我没有建议他不学习标准流。
operator>>界面非常微妙。当您可以使用std::getline()(也适用于标准 I/O 流...)时,为什么要让自己陷入危险之中?