CppBuzz.com
  
Home C C++ Java Python Perl PHP Spring SQL Javascript Linux Forum

You are here : Home » Solved Programs on C++ » C++ program to split vector into groups

C++ program to split vector into groups

This C++ program takes comman separated string as input, parse it into Vector of int and then print it in groups of 2 and 1 values.

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

void print2values(int a, int b);
void print1value(int a);

int main()
{
std::string str;
std::cout<<"\n Enter comma separated no : ";
std::cin>>str;

std::vector<int> vect;
std::stringstream ss(str);

int i;

std::cout<<"\n\t";

while (ss >> i)
{
vect.push_back(i);

if (ss.peek() == ',')
    ss.ignore();
}

for (i=0; i< vect.size(); i++)

if(i <= vect.size()-2){
    print2values(vect.at(i), vect.at(i+1));
    i++;
}
else{
    print1value(vect.at(i));
}
        
}

void print2values(int a, int b){
    std::cout<<a<<" "<<b<<" ";
}

void print1value(int a){
    std::cout<<a<<" ";
}
C++ program to parse comma separated string of no to Vector