Cannot convert a string of integers to integers in C++

112 views Asked by At

I am currently at hand have a function at hand within a class, User::User(string id, string ratings). I am attempting to currently store the string "1 5 5 3 0 -5 0 5" (which is the parameter for ratings, id is already dealt with) into a vector which cannot be changed called vector(int) <--integers ratings as a vector of 8 integers seen in the string. What is the best way to iterate through this string and store the individual values(negatives included)?

2

There are 2 answers

0
Rémi On
#include <sstream>
#include <vector>
#include <iostream>

int main()
{
    std::istringstream is("1 5 5 3 0 -5 0 5");
    std::vector<int> v;

    int n;
    while (is >> n)
        v.push_back(n);

    for (size_t i = 0; i < v.size(); i++)
        std::cout << v[i] << '\n';

    return 0;
}
0
bpw1621 On

This problem is a canonical use-case for stream iterators

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>


int main()
{
  std::istringstream iss{ "1 5 5 3 0 -5 -5" };
  std::vector< int > v;

  std::copy( std::istream_iterator< int >{ iss },
             std::istream_iterator< int >{},
             std::back_inserter( v ) );

  std::copy( std::begin( v ),
             std::end( v ),
             std::ostream_iterator< int >( std::cout, " " ) );
}