Split string that contains delimeter and store into vector pair

Jul 15, 2018 at 1:01pm
i have been searching for ages on how to split string that is separated by delimeter and storing them into vector pair.

For example, i have a string that contains the following information

"3:4"


and i have the following vector

vector<pair<int, int>> vect.

How do i split the string that is separated by the delimeter and storing each individual data into the vector pair such that the first int contains 3, and the second contain 4.
Jul 15, 2018 at 1:08pm
is the format of string always like you have given?
Jul 15, 2018 at 1:09pm
Is the delimiter fixed
Jul 15, 2018 at 1:11pm
yes. the delimeter will always be fixed and the string will always only contain 2 number separated by the delimeter.
Jul 15, 2018 at 1:15pm
then you should simply store the value of string before ':' int first int and value after that in the second int (ofcourse after converting them to ints)
Jul 15, 2018 at 1:16pm
how do i even store the value of string before the delimeter into the int variable. ? i do know how to convert them which is via atoi function.
Jul 15, 2018 at 1:22pm
1
2
3
4
5
6
7
8
int num1=0,num2=0,flag=0;
vector<pair<int,int> > vect;
for(int i=0;i<s.length();i++){
  if(s[i]==':') flag=1;
  else if(flag==0) num1=num1*10+s[i]-'0';
  else if(flag==1) num2=num2*10+s[i]-'0';
}
vect.push_back({num1,num2});


I think this would work.
Jul 15, 2018 at 1:28pm
it works. thank you. do you mind if you explain a little bit about your code?
Jul 15, 2018 at 3:26pm
check yourself by taking any example and going through the code stepwise: eg, check yourself for the string "234:987", i hope you will get the intuition.
Jul 15, 2018 at 4:24pm
Why not just use a stringstream to process the string?
1
2
3
4
5
6
7
std::string my_pair{"1234:3323"};
std::stringstream sin(my_pair);
int num1, num2;
char delimiter;
sin >> num1 >> delimiter >> num2;
vect.push_back({num1, num2};
Jul 15, 2018 at 6:09pm
This stringstream stuff I have never used. Could you tell me about how it works?
Jul 15, 2018 at 7:20pm
closed account (E0p9LyTq)
An example of how to use a stringstream here at cplusplus:
http://www.cplusplus.com/reference/sstream/stringstream/stringstream/

All you wanted to know about stringstream:
https://en.cppreference.com/w/cpp/io/basic_stringstream

With an example of extracting from a string:
https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
Topic archived. No new replies allowed.