How to check std::string if its indeed an integer?

前端 未结 3 1638
夕颜
夕颜 2020-12-07 02:41

The following code converts an std::string to int and the problem lies with the fact that it cannot discern from a true integer or just a random st

3条回答
  •  不思量自难忘°
    2020-12-07 03:25

    You may try to use Boost lexical_cast, it will throw an exception if the cast failed.

    int number;
    try
    {
         number = boost::lexical_cast(str);
    }
    catch(boost::bad_lexical_cast& e)
    {
        std::cout << str << "isn't an integer number" << std::endl;
    }
    

    EDIT Accorinding to @chris, You may also try to use std::stoi since C++11. It will throw std::invalid_argument exception if no conversion could be performed. You may find more information here: std::stoi

提交回复
热议问题