输入验证函数

时间:2016-09-13 02:50:00

标签: c++ function

我对c ++和编码很新。目前,我正在努力创造一个“疯狂的自由”"程序基本上要求用户输入(2个不同的名词和2个不同的形容词),然后使用这些输入来生成行"非常。它看起来像一个。"

当用户运行程序时,应该询问他们"你想玩游戏吗?输入y表示是,n表示否#34;。如果用户以y响应,则应该运行madlib函数并且应该给出它们的输入。故事结束并返回给用户后,应再次提示他们是否要继续播放(同样,y表示是,n表示否)。他们应该能够根据自己的需要多次玩游戏,直到他们回答“n”为止。到目前为止,这最后一部分是最大的斗争。我知道如何在一个主函数中创建程序,但我的目标是为主函数调用的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;
    }
}

2 个答案:

答案 0 :(得分:0)

while (response == 'y'){
   int madLib();

while循环中,这声明了一个名为madLib()的函数。

注意这与执行名为madLib()的函数不同。这只是一个声明。事实陈述它存在。

但是,向全世界宣称这个功能存在是不够的。你显然更喜欢执行它。在这种情况下,那只是:

    madLib();

答案 1 :(得分:0)

    1. 修复问题的格式。
    1. 试试这个吗?

将该函数作为参数输入到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;
}