【问题标题】:Turning string input into boolean将字符串输入转换为布尔值
【发布时间】:2021-01-01 20:11:16
【问题描述】:

我试图弄清楚如何将“是”或“是”或“否”的用户文本输入转换为布尔真/假变量。我想知道我是否可以使用开关功能来做到这一点。

【问题讨论】:

  • 不幸的是,您不能在字符串上switch。我会将字符串转换为全部小写(或全部大写)以减少所需的比较次数,然后使用if
  • 不,switch 语句不能与字符串一起使用。
  • 从您知道如何做的事情开始,然后朝着您的目标努力。你的出发点是什么?

标签: c++ string char switch-statement boolean


【解决方案1】:

您可以使用以下方法来做到这一点。

#include <iostream>
#include <string>
#include <algorithm>    // For the std::transform() function.

int main()
{
    std::string inCommand;

    std::getline(std::cin, inCommand);
    std::transform(inCommand.begin(), inCommand.end(), inCommand.begin(),
        [](unsigned char c) { return std::tolower(c); });
    
    bool command = inCommand == "yes";
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 2012-03-10
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多