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

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

基本上,这个程序根据人们对提示的 react 来输出一个人应该吃什么糖果。如果他们喜欢巧克力,程序会询问他们是否喜欢坚果。如果他们对巧克力说"is",对坚果说“不”,他们就会得到M&M巧克力 bean 。如果他们同意巧克力和坚果,他们就会得到花生巧克力 bean 。如果他们对巧克力说不,他们就会得到彩虹糖。

无论我为 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。

如果我计算<< ChocLover;也没有打印任何内容。

最佳答案

cin.get(chocLover) 执行未格式化的输入,它正在读取作为先前输入的一部分输入的换行符。使用格式化输入运算符忽略空格:

cin>>chocLover;

关于C++:条件未应用于简单的嵌套 if-then-else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22978433/

相关文章:

c++ - 为什么只有当它有模板推导时我才能将左值绑定(bind)到通用引用?

java - 在一个 if 语句(+ XOR,正则表达式)中缩短多个 AND + OR

python-3.x - 使用 for 循环遍历字节对象 python 3x

c++ - FFmpeg编译opus错误

c++ - is_standard_layout 有什么用?

r - 使用for循环返回变量名-R中的变量均值

javascript - for 循环与 if 条件

javascript - 通过 For 循环选择和添加函数到 Div

javascript - 来自 CoderSchool 的 JavaScript 中的闭包

c++ - 最简单的 C++11 容器是什么?