How can I convert a std::string to int?

后端 未结 19 1615
梦毁少年i
梦毁少年i 2020-11-22 02:10

Just have a quick question. I\'ve looked around the internet quite a bit and I\'ve found a few solutions but none of them have worked yet. Looking at converting a string to

19条回答
  •  佛祖请我去吃肉
    2020-11-22 03:06

    1. std::stoi

    std::string str = "10";  
    int number = std::stoi(str); 
    

    2. string streams

    std::string str = "10";  
    int number;  
    std::istringstream(str) >> number
    

    3. boost::lexical_cast

    #include 
    std::string str = "10";  
    int number;
        
    try 
    {
        number = boost::lexical_cast(str);
        std::cout << number << std::endl;
    }
    catch (boost::bad_lexical_cast const &e) // bad input
    {
        std::cout << "error" << std::endl;
    }
    

    4. std::atoi

    std::string str = "10";
    int number = std::atoi(str.c_str()); 
    

    5. sscanf()

     std::string str = "10";
     int number;
     if (sscanf(str .c_str(), "%d", &number) == 1) 
     {
         std::cout << number << '\n';
     } 
     else 
     {
         std::cout << "Bad Input";
     }
    

提交回复
热议问题