Switch语句输出错误的成本值

时间:2014-09-26 16:23:43

标签: c++ switch-statement sleep cout

当我尝试在Microsoft Visual Studio C ++上运行此代码时;它运行但输出的成本值是错误的。这是为什么?我确实意识到我没有包含默认语句,并且我声明cost两次,这是因为我得到了cost没有声明值的调试错误,所以我假设正在进行是switch语句没有处理因为它有些怎么不理解
     cout << "Pizza"; 我该如何解决这个问题?

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <Windows.h>
#include <string>

using namespace std;

int main()
{
    int a, b, c, d, e, f, m, p, k,  User_Input, Pizza , cost;
    a = 0;
    b = 0;
    c = 0;
    d = 0;
    e = 0;
    f = 0;
    k = 0;
    cost = 0;

    cout << "What is your favorite vegetarian food from the list below?" << endl;
    Sleep(1500);
    cout << "Pizza\n";
    Sleep(200);
    cout << "IceCream\n";

    cin >> User_Input;
    switch (User_Input)
    {
    case 1:
        cout << "Pizza";
        cost = 5;
        break;
    case 2:
        cout << "IceCream";
        cost = 5;
        break;

    }


    Sleep(2000);
    cout << "The total cost will be: " << cost;
    cout << "\n\n\n\t\t\t";

    return 0;


}

1 个答案:

答案 0 :(得分:2)

User_Input的类型为&#34; int&#34;,如果您尝试通过cin读取该字符串到该变量,您将获得意外结果。您可能想要做的是:

  • 读入字符串并进行字符串比较
  • 读入字符串,转换为int,然后执行switch语句

简化示例:

#include <iostream>
#include <string>
int main()
{
        std::string user_input;
        int cost = 0;
        std::cout << "What is your favorite vegetarian food from the list below?\nPizza\nIceCream\n";
        std::cin >> user_input;
        if(user_input == "Pizza") {
                cost = 5;
        } else if (user_input == "IceCream") {
                cost = 10;
        }
        std::cout << "The total cost will be: " << cost << std::endl;
        return 0;
}