0

我有一个代码应该使用用户输入来订购比萨饼。

#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 函数不等待任何用户输入,而是输入一个空字符串。为什么要这样做?

4

0 回答 0