How can I convert a string of integers to a vector full of int?

I know there have been other questions asked about this, however I have used these other resources to come up with what I have now and I get an error that I cannot understand. Also, keep in mind that I am a C ++ beginner. That being said, I have a very large string filled with integers formatted like this: newString = "12 -34 50 2 -102 13 78 9"

(the actual string is much larger). Then I try to create a function using transform()

to convert a string to an int vector:

int convertString(){

    istringstream is(newString);
    vector<int> intVector;
    transform(istream_iterator<string>( is ),
              istream_iterator<string>(),
              back_inserter( intVector ),
              []( const string &newString ){ return ( stoi( newString ) ); } );//This is the line indicated in the error!
    for(int x : intVector )
        cout << x << ' '<<endl;

    return 0;
    }

      

The error I'm getting is that the expected expression is expected on the specified error line ... Any ideas how to fix this?

Thanks in advance and just let me know if anything is unclear!

+3


source to share


1 answer


Assuming you are reasonably sure that the entry contains only a properly formatted int

s ((or can live with just stopping reading when / if found something different from reading a whole), there is no need transform

he istream_iterator

can perfectly cope with the transformation. You can initialize a vector directly from iterators, giving code like this:

std::istringstream is(newString);
std::vector<int> intVector { std::istream_iterator<int>(is), 
                             std::istream_iterator<int>()};

      



This will differ from your version in one respect: if you supply a string stoi

that it cannot convert to an integer, it will throw an exception - invalid_argument

if it contains something like ac;

it cannot convert to an integer at all, or out_of_range

if it contains something like 50 digits that results in a result that will not match the target type.

+7


source







All Articles