【问题标题】:Comparing data types比较数据类型
【发布时间】:2011-03-26 13:27:55
【问题描述】:
int item;
cin >> item;

这在我的代码中,但我希望用户能够输入整数或字符串。这基本上就是我想做的:

if(item.data_type() == string){
  //stuff
}

这可能吗?

【问题讨论】:

    标签: c++ types comparison


    【解决方案1】:

    您不能完全做到这一点,但只要多做一些工作,您就可以做类似的事情。如果您安装了 Boost 库,则以下代码有效。它可以在没有提升的情况下完成,但是这样做很乏味。

    #include <boost/lexical_cast.hpp>
    
    main() {
        std::string val;
        std::cout << "Value: " << std::endl;
        std::cin >> val;
        try {
            int i = boost::lexical_cast<int>(val);
            std::cout << "It's an integer: " << i << std::endl;
        }
        catch (boost::bad_lexical_cast &blc) {
            std::cout << "It's not an integer" << std::endl;
        }
    }
    

    【讨论】:

      【解决方案2】:

      不,但你可以输入字符串,然后将其转换为整数,如果它是整数。

      【讨论】:

      • 这就是我要找的东西 - 我该怎么做?
      【解决方案3】:

      【讨论】:

      • RTTI 让他识别 am 对象的类型。我认为这对他的处境没有帮助。就 RTTI 而言,字符串“123”仍然是一个字符串。
      【解决方案4】:

      您所做的不是重视 C++ 代码。它不会编译!


      你的问题是:

      这在我的代码中,但我希望用户能够输入整数或字符串

      然后这样做:

      std::string input;
      cin >> input;
      int intValue;
      std::string strValue;
      bool isInt=false;
      try 
      {   
          intValue = boost::lexical_cast<int>(input);
          isInt = true;
      }
      catch(...) { strValue = input; }
      
      if ( isInt) 
      {
         //user input was int, so use intValue;
      }
      else
      {
         //user input was string, so use strValue;
      }
      

      【讨论】:

      • 我已经安装了 boost,但我不想将它用于这个在命令中运行的小型 RPG。
      猜你喜欢
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2021-05-04
      • 2010-12-16
      相关资源
      最近更新 更多