ユーザー入力を使用してピザを注文するコードがあります。
#include<iostream>
#include<string>
using namespace std;
int main()
{
double totalCosts = 0;
// PIZZA
cout << "What size is your first pizza?\n"
"small: $8.00\n"
"medium: $10.00\n"
"large: $12.00\n";
string currentSize = "";
getline(cin, currentSize);
cout << "\n";
if(currentSize == "small")
{
totalCosts += 8;
}
else if(currentSize == "medium")
{
totalCosts += 10;
}
else if(currentSize == "large")
{
totalCosts += 12;
}
else
{
cout << "invalid size: " << currentSize;
return 0;
}
string pizzaToppings = "";
cout << "Choose from the following toppings:\n"
"onions: $1.00\n"
"peppers: $1.20\n"
"ham: $1.50\n"
"hamburger: $1.25\n"
"pepperoni: $1.55\n"
"salami: $1.63\n"
"sausage: $1.44\n";
getline(cin, pizzaToppings);
cout << "\n";
if(pizzaToppings.find("onions") != string::npos)
{
totalCosts += 1;
}
else if(pizzaToppings.find("peppers") != string::npos)
{
totalCosts += 1.2;
}
else if(pizzaToppings.find("ham") != string::npos)
{
totalCosts += 1.5;
}
else if(pizzaToppings.find("hamburger") != string::npos)
{
totalCosts += 1.25;
}
else if(pizzaToppings.find("pepperoni") != string::npos)
{
totalCosts += 1.55;
}
else if(pizzaToppings.find("salami") != string::npos)
{
totalCosts += 1.63;
}
else if(pizzaToppings.find("sausage") != string::npos)
{
totalCosts += 1.44;
}
else
{
cout << "Choose at least one valid topping";
return 0;
}
// DELIVERY AND FINAL PRINTOUT
string needToDeliver = "";
cout << "Do you want delivery? yes/no\n";
getline(cin, needToDeliver);
cout << "\n";
if(needToDeliver == "yes")
{
totalCosts += 3;
cout << "What is your address?";
getline(cin, needToDeliver); // address doesn't matter
}
cout << "Your total cost is: $" << totalCosts << ". Thank you for buying C++ Pizza.";
return 0;
}
このコードは、次の出力を提供します。
初めてのピザのサイズは?
小: $8.00
ミディアム: $10.00
大: $12.00
無効なサイズ:
私が考えているのは、最初の getline 関数がユーザーの入力を待っておらず、代わりに空の文字列を入力していることです。なぜこれを行うのですか?