2
기본적으로이 프로그램은 프롬프트에 대한 응답에 따라 사람이 가져야하는 사탕을 출력합니다. 그들이 초콜릿을 좋아한다면, 프로그램은 그들이 너트를 좋아하는지 물어 봅니다. 초콜렛에 '예스'라고 말하면 견과류에는 'M &'이 붙습니다. 그들이 초콜렛과 견과류에 예스라고 말하면, 그들은 땅콩을 얻습니다. M & Ms. 그들은 초콜릿을 거부하면 Skittles를 얻습니다.C++ : 간단한 중첩 if-then-else 문에는 조건이 적용되지 않습니까?
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;'. 그것은 질문에 대답하지 않지만 지금은 해결할 수 있습니까? – Suedocode