How do I convert vector of strings into vector of integers in C++?

前端 未结 7 2060
甜味超标
甜味超标 2021-01-23 01:10

I have a vector of strings. Need help figuring out how to convert it into vector of integers in order to be able to work with it arithmetically. Thanks!

#include         


        
7条回答
  •  太阳男子
    2021-01-23 01:24

    There are mulitple ways of converting a string to an int.

    Solution 1: Using Legacy C functionality

    int main()
    {
        //char hello[5];     
        //hello = "12345";   --->This wont compile
    
        char hello[] = "12345";
    
        Printf("My number is: %d", atoi(hello)); 
    
        return 0;
    }
    

    Solution 2: Using lexical_cast(Most Appropriate & simplest)

    int x = boost::lexical_cast("12345"); 
    

    Surround by try-catch to catch exceptions.

    Solution 3: Using C++ Streams

    std::string hello("123"); 
    std::stringstream str(hello); 
    int x;  
    str >> x;  
    if (!str) 
    {      
       // The conversion failed.      
    } 
    

提交回复
热议问题