如何将IF语句与字符串用户输入一起使用?

时间:2019-11-03 21:45:07

标签: c++ string

我是C ++新手,已经花了半天的时间进行了谷歌搜索。大多数帖子似乎模糊或复杂。而且我感觉有一种更简单的方法可以做到这一点。任何帮助表示赞赏。 一个简单的程序,可根据用户输入的状态计算税金:

#include <iostream>

int main()
{
    std::cout << "Enter your order amount: ";
    int amount{};
    std::cin >> amount;

    std::cout << "Which state do you reside in? ";
    std::string state{};
    std::cin >> state;

    if (state == "WI") //THIS IS SIMILAR TO HOW I WOULD DO IT IN PYTHON | C++ doesn't work this way
        std::cout << "Your tax is 5.0$" << std::endl;
        std::cout << "Your total is " << amount + 5.0;

    else
        std::cout << "Your tax is 0.0$" << std::endl;
        std::cout << "Your total is " << amount;

    return 0;
}

1 个答案:

答案 0 :(得分:4)

请注意,将{}添加到if和else后面的语句分组

#include <iostream>

int main()
{
    std::cout << "Enter your order amount: ";
    int amount{};
    std::cin >> amount;

    std::cout << "Which state do you reside in? ";
    std::string state{};
    std::cin >> state;

    if (state == "WI")
    {
        std::cout << "Your tax is 5.0$" << std::endl;
        std::cout << "Your total is " << amount + 5.0;
    }
    else
    {
        std::cout << "Your tax is 0.0$" << std::endl;
        std::cout << "Your total is " << amount;
    }

    return 0;
}

if (condition)else之后,该语言仅允许一个语句。大括号{}将一系列语句括入复合语句。

有关更清晰的语言,请参见复合语句https://en.cppreference.com/w/cpp/language/statements