我知道这个问题之前已经在这个网站上被问过,但我似乎无法掌握如何让它与我的特定程序一起工作。
本质上,我正在创建一种小型 MadLibs 类型的游戏,玩家必须输入某些内容才能将其融入故事中。现在,如果用户输入中没有空格,则效果非常好,但是第二次有人输入空格时,程序可以跳过整个问题。
这是我的代码:
int main(){
int selection;
//News Report Variables
std::string nrfullname;
std::string nrcrime;
std::string nradjective;
std::string nrtown;
std::string nrpluralnoun;
std::string nrnounnotplace;
std::string nrverb;
std::string nradjective2;
std::string nrfullname2;
std::string nrnounnotplace2;
std::cout << "Welcome to Mad Libs! Please, pick a story!" << std::endl;
std::cout << "1. News Report" << std::endl;
std::cin >> selection;
if (selection == 1) {
std::cout << "We need a full name of someone." << std::endl;
std::cin >> nrfullname;
std::cout << "We need a crime." << std::endl;
std::cin >> nrcrime;
std::cout << "We need an adjective." << std::endl;
std::cin >> nradjective;
std::cout << "We need a town." << std::endl;
std::cin >> nrtown;
std::cout << "We need a plural noun." << std::endl;
std::cin >> nrpluralnoun;
std::cout << "We need a noun that is NOT a place." << std::endl;
std::cin >> nrnounnotplace;
std::cout << "We need a verb." << std::endl;
std::cin >> nrverb;
std::cout << "We need another adjective." << std::endl;
std::cin >> nradjective2;
std::cout << "We need a full name of someone else." << std::endl;
std::cin >> nrfullname2;
std::cout << "We need another noun that is NOT a place." << std::endl;
std::cin >> nrnounnotplace2;
}
正如您可能想象的那样,大多数人会选择在要求某人全名的地方留一个空格(我当然知道我会的)。如果他们输入该空格,它就会跳过“犯罪”问题,直接转到形容词问题。
如果您能向我展示如何使其正常工作,那将是有益的,因为它让我有点压力,并且我尝试过的所有解决方案要么使问题变得更糟,要么没有采取任何措施来帮助解决问题它。
代替std::cin >> nrfullname
,你只需要使用std::getline(std::cin, nrfullname [, delim])
std::getline()
从输入流中提取字符并将结果存储在nrfullname
直到下一个分隔符。如果不指定分隔符,'\n'
用来。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)