gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:45:00 24 4
gpt4 key购买 nike

基本上,这个程序根据他们对提示的 react 输出一个人应该吃什么糖果。如果他们喜欢巧克力,程序会询问他们是否喜欢坚果。如果他们对巧克力说是,对坚果说不,他们就会得到 M&M's。如果他们对巧克力和坚果说"is",他们就会得到花生 M&M 巧克力 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com