getline()不等待用户输入

时间:2013-04-28 03:26:23

标签: c++ getline

我有一个代码,应该使用用户输入来获取披萨的订单。

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

0 个答案:

没有答案