C ++:条件没有应用于简单的嵌套if-then-else语句?

时间:2014-04-10 04:04:56

标签: c++ if-statement for-loop conditional-statements

基本上,这个程序根据他们对提示的回答输出一个人应该拥有的糖果。如果他们喜欢巧克力,程序会询问他们是否喜欢坚果。如果他们对巧克力说“是”而对坚果说“不”,他们会得到M& M's。如果他们对巧克力和坚果说“是”,他们会得到花生M& Ms。如果他们对巧克力说“不”,他们会得到Skittles。

无论我为chocLover投入什么,我都会将Skittles作为输出。

源代码:

#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;

int main()
{
    const int SNACK_SIZE = 15;
    const int DRINK_SIZE = 6;


    char guestName[30];
    int  guestAge;
    char chocLover;
    char nutLover;

    int  count;

    char snack[15];
    char drink[6];

    for(count = 1; count <=12; count=count+1)
    {
    cout << left << "Guest #" << count << ":" << endl;

    cout << setw(31) << "What is your friend's name?";
    cin.getline(guestName,30);

    cout << setw(31) << "How old is your friend?";
    cin  >> guestAge;

    cout << setw(31) << "Do they like chocolate (Y/N)?";
    cin.get(chocLover);
    cin.ignore(1000,'\n');

    if(chocLover == 'Y')
    {
        cout << setw(31) << "Do they like nuts (Y/N)?";
        cin.get(nutLover);

        if(nutLover == 'Y')
        {
            strncpy(snack,"Peanut M & M\'s",SNACK_SIZE);
        }
        else
        {
            strncpy(snack,"M & M\'s",SNACK_SIZE);
        }
    }
    else
    {
        strncpy(snack,"Skittles",SNACK_SIZE);
    }

    if(guestAge <= 21)
    {
        if(guestAge < 6)
        {
            strncpy(drink,"juice",DRINK_SIZE);
        }
        else
        {
            strncpy(drink,"soda",DRINK_SIZE);
        }
    }
    else
    {
        strncpy(drink,"wine",DRINK_SIZE);
    }

    cout << endl;
    cout << "You should serve " << guestName << " " << snack << " and ";
    cout << drink << "." << endl << endl << endl;
    }

    return 0;
}

输出:

Guest #1:
What is your friend's name?    Guest
How old is your friend?        18
Do they like chocolate (Y/N)?  Y

You should serve Guest Skittles and soda.


Guest #2:
What is your friend's name?    Guest
How old is your friend?        20
Do they like chocolate (Y/N)?  Y

You should serve Guest Skittles and soda.

等等,直到达到#12。

如果我cout&lt;&lt; chocLover;也没有任何印刷品。

1 个答案:

答案 0 :(得分:2)

cin.get(chocLover)执行无格式输入,它会读取作为上一个输入的一部分输入的换行符。使用格式化的输入运算符忽略空格:

cin >> chocLover;