1

I have a string that contains 3 numbers separated by commas (for example "10,32,52") and I would like to store each number in 3 different int variables, but I just know how to store the first one using the code below. Can you tell me please how can I store the next two? Thanks in advance.

string numbers= "10,32,52";
string first_number_s= numbers.substr(0,2);
int first_number_n= stoi(first_number_s);
drescherjm
  • 10,365
  • 5
  • 44
  • 64

1 Answers1

0

You could stream the input string into a string stream and use std::getline to extract strings separated by a delimiter, in this case comma, converting each one to an integer:

#include <sstream>
#include <string>

std::string numbers = "10,32,52";
std::istringstream sstream(numbers);
std::string temp;
std::vector<int> nums;
while (std::getline(sstream, temp, ','))
{
    nums.push_back(std::stoi(temp));
}
jignatius
  • 6,304
  • 2
  • 15
  • 30