-3

I find it hard to do all the string manipulation and then parsing into an array of integers in c++ while we could get away with only a single line in python.

whats the easiest way to split the string of integers into an array of integers in c++ ?

Natesh bhat
  • 12,274
  • 10
  • 84
  • 125
  • 1
    you might want to share what your string actually looks like – maxbachmann May 28 '19 at 08:09
  • 3
    This is really two questions; "how do I split a string in C++" and "how do I convert strings to integers in C++". You should easily be able to find answers to both of those questions with little searching. – Markus Meskanen May 28 '19 at 08:12

2 Answers2

3

There are many options to do this. For example using standard stream this could be achieved using:

#include <vector>
#include <string>
#include <sstream>

std::string s = "1 2 3";
std::vector<int> result;
std::istringstream iss(s);
for(int n; iss >> n; ) 
    result.push_back(n);
maxbachmann
  • 2,862
  • 1
  • 11
  • 35
0

The question is too broad and there are many solutions depending on the format of your string. In the case that you want to split a string using a custom delimiter and convert it to integers (or whatever) I personally use the following function (I have absolutely no idea if there are faster ways to do it):

void split_string_with_delim(std::string input, std::string delimiter, std::vector<std::int> &output){
    ulong pos;
    while ((pos = input.find(delimiter)) != std::string::npos) {
        std::string token = input.substr(0, pos);
        output.push_back(std::stoi(token));
        input.erase(0, pos + delimiter.length());
    }
    output.push_back(std::stoi(input));
}
Greg K.
  • 686
  • 1
  • 5
  • 18