How to input a comma separated string in C++?

Given an input string which is comma-separated instead of space, the task is to parse this input string in C++.

First, let us understand what difference does it create if the input string is comma-separated.
Taking input a whitespace-separated string

Taking input a whitespace-separated string in C++ is very easy. The program to do so is:



filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    string str;
  
    // Get the string
    getline(cin, str);
  
    // Print the words
    istringstream ss(str);
    do {
        string word;
        ss >> word;
        cout << word << endl;
    } while (ss);
}

chevron_right


Input:

1 2 3 4 5 6

Output:

1
2
3
4
5
6

Why can’t we use the above code for comma-separated input string?
The above code works fine for a whitespace-separated input string, but for a comma-separated input string, it won’t work as expected, because the program will take complete input as a single word in the string.

Input:

1, 2, 3, 4, 5, 6

Output:

1, 2, 3, 4, 5, 6

How to input a comma separated string?
Now inorder to input a comma separated string, following approach can be used:

  1. Get the string to be taken as input in stringstream
  2. Take each character of the string one by one from the stream
  3. Check if this character is a comma (‘, ‘).
  4. If yes, then ignore that character.
  5. Else, Insert this character in the vector which stores the words

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to input
// a comma separated string
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Get the string
    string str = "11,21,31,41,51,61";
  
    vector<int> v;
  
    // Get the string to be taken
    // as input in stringstream
    stringstream ss(str);
  
    // Parse the string
    for (int i; ss >> i;) {
        v.push_back(i);
        if (ss.peek() == ',')
            ss.ignore();
    }
  
    // Print the words
    for (size_t i = 0; i < v.size(); i++)
        cout << v[i] << endl;
}

chevron_right


Output:

11
21
31
41
51
61


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.