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

后端 未结 19 1660
梦毁少年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:03

    Admittedly, my solution wouldn't work for negative integers, but it will extract all positive integers from input text containing integers. It makes use of numeric_only locale:

    int main() {
            int num;
            std::cin.imbue(std::locale(std::locale(), new numeric_only()));
            while ( std::cin >> num)
                 std::cout << num << std::endl;
            return 0;
    }
    

    Input text:

     the format (-5) or (25) etc... some text.. and then.. 7987...78hjh.hhjg9878
    

    Output integers:

     5
    25
    7987
    78
    9878
    

    The class numeric_only is defined as:

    struct numeric_only: std::ctype 
    {
        numeric_only(): std::ctype(get_table()) {}
    
        static std::ctype_base::mask const* get_table()
        {
            static std::vector 
                rc(std::ctype::table_size,std::ctype_base::space);
    
            std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
            return &rc[0];
        }
    };
    

    Complete online demo : http://ideone.com/dRWSj

提交回复
热议问题