0

I am trying to convert a string into a vector

#include <iostream>
#include <vector>
using namespace std;
int main() {
    string nums = "1,+2,-3";
    vector<int> a;
}

How do I convert nums into a vector of integers? An example of this in python would be:

string = 1,223,132,34
list = string.split(",")
kiner_shah
  • 3,445
  • 6
  • 25
  • 36
GoatMode
  • 13
  • 2
  • 1
    You can use std::stringstream along with std::getline. – kiner_shah Feb 02 '22 at 11:22
  • 2
    This may be done with `std::getline()` or `std::istringstream`. – Scheff's Cat Feb 02 '22 at 11:22
  • There's `std::views::split` but it belongs to not-yet-fully-supported area of the standard. – bipll Feb 02 '22 at 11:25
  • 1
    Your python code doesn't work like that, even after fixing the missing `"`. You need to map it to `int` explicitly, otherwise you have a list of strings, not a list of integers. Note that the linked duplicates also only take care of the splitting into substrings, not the type conversion. – user17732522 Feb 02 '22 at 11:25
  • I.e. the python example should be `string = "1,223,132,34"` `list = [int(num) for num in string.split(",")]` – Caleth Feb 02 '22 at 11:35

0 Answers0