我应该做些什么改变,当我输入“a”表示面包时,当我输入“b”时它会说葡萄酒?

时间:2016-06-22 02:17:10

标签: c++ if-statement

这是我的代码。我在if语句中输入的公式不起作用。

#include <iostream>
using namespace std;

int main(){

    int value;

    cout << "a) Bread" << endl;
    cout << "b) Wine" << endl;
    cout << endl;
    cout << "Please enter the letter of the type of product you want to buy: " << endl;
    cin >> value;

    if(value == a){
        cout << "You chose bread";
    } else{
        cout << "You chose wine";
    }

    return 0;
}

2 个答案:

答案 0 :(得分:2)

您应始终包含代码所带来的错误,以及您尝试解决问题的所有内容。

您的错误是,如果您要查看'a',则需要用单引号将其括起来。您正尝试将value与名为a的非现有变量进行比较。

答案 1 :(得分:2)

#include <iostream>
using namespace std;

int main(){

    char value; // int => char

    cout << "a) Bread" << endl;
    cout << "b) Wine" << endl;
    cout << endl;
    cout << "Please enter the letter of the type of product you want to buy: " << endl;
    cin >> value;

    if(value == 'a'){ // a => 'a'
        cout << "You chose bread";
    } else{
        cout << "You chose wine";
    }

    return 0;
}