一般来说,我对c++和编程都是非常陌生的。目前,我正在努力创建一个"Mad Lib“程序,它本质上是要求用户输入(两个不同的名词和两个不同的形容词),然后使用这些输入来生成行”非常。它看起来像一个。“
当用户运行程序时,他们应该被问到“你想玩游戏吗?输入y表示是,n表示否”。如果用户的响应是y,那么madlib函数应该运行,并且他们应该给出他们的输入。一旦故事结束并返回给用户,应该再次提示他们是否要继续播放(同样,y表示是,n表示否)。他们应该能够多次玩这个游戏,直到他们回答'n‘为止。到目前为止,最后这部分是最大的斗争。我知道如何在一个main函数中创建程序,但我的目标是对可由main函数调用的n和y函数进行某种类型的输入验证。有什么想法吗?这是我到目前为止所知道的:
#include <iostream>
using namespace std;
int madLib(){
string noun, adjective, noun1, adjective1;
cout << "enter a noun" << endl;
cin >> noun;
cout << "enter an adjective" << endl;
cin >> adjective;
cout << "enter another noun" << endl;
cin >> noun1;
cout << "enter andother adjective" << endl;
cin >> adjective1;
cout << noun << " is very " << adjective << ". It looks like a " << adjective1 << " " << noun1 << "." << endl;
}
int main(){
char response;
cout << "type y for yes and n for no" << endl;
cin >> response;
while (response == 'y'){
int madLib();
cout << "play again?" << endl;
cin >> response;
}
if (response == 'n'){
cout << "goodbye." << endl;
}
}
发布于 2016-09-13 10:54:21
while (response == 'y'){
int madLib();
在while
循环中,它声明了一个名为madLib()
的函数。
注意:这与执行一个名为madLib()
的函数不是一回事。这只是一份声明。它存在的事实的陈述。
然而,向世界宣布这个功能的存在是不够的。您显然更喜欢执行它。在这种情况下,这将是简单的:
madLib();
发布于 2016-09-13 10:57:15
格式
将函数作为参数输入到while循环:
while(inputValid()) {
madLib();
// do something..
}
其中,inputValid函数为:
bool inputValid() {
cout << "type y for yes and n for no" << endl;
char response; cin >> response;
if ( response == 'y' ) return true;
else if ( response == 'n' ) return false;
}
https://stackoverflow.com/questions/39461531
复制相似问题