The Wayback Machine - https://web.archive.org/web/20240827182010/https://www.geeksforgeeks.org/how-to-input-a-comma-separated-string-in-c/
Open In App

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

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
52.61%
16.2K

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:

C++




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


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:

CPP




// 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;
}


Output: 

11
21
31
41
51
61

 

Time complexity: O(N).

Auxiliary Space: O(N).



Similar Reads

Program to Parse a comma separated string in C++
Given a comma-separated string, the task is to parse this string and separate the words in C++. Examples: Input: "1,2,3,4,5" Output: 1 2 3 4 5 Input: "Geeks,for,Geeks" Output: Geeks for Geeks Approach: Get the string in stream - stringstreamCreate a string vector to store the parsed wordsNow till there is a string in stringstream, checked by good()
1 min read
Convert Array of Integers to Comma-Separated String
Given an array of integers arr[] of size N, return the string representation of integers separated by comma and a space. The last element should be separated by " and ", instead of comma and a space. Examples: Input : arr=[10, 20, 30, 40, 50]Output: "10, 20, 30, 40 and 50" Input: arr = [2,5]Output : "2 and 5" Input: arr = [10]Output: "10" Approach:
4 min read
Kth space-separated number from a given string
Given a string S consisting of space-separated integers, the task is to extract the Kth number present in the string. Note: The string contains at least K numbers in it. Examples: Input: S = "12 13 15", K= 3Output: 15Explanation: The 3rd integer in the above string is 15. Input: S = "10 20 30 40", K = 2Output: 20Explanation: The 2nd integer in the
10 min read
Check if any pair of consecutive 1s can be separated by at most M 0s by circular rotation of a Binary String
Given a binary string S of length N and a positive integer M, the task is to check if it is possible to rotate the string circularly any number of times such that any pair of consecutive 1s are separated by at most M 0s. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: S = "101001", M = 1Output: YesExplanation: Right shi
8 min read
How can we use Comma operator in place of curly braces?
In C and C++, comma (, ) can be used in two contexts: Comma as an operator Comma as a separator But in this article, we will discuss how a comma can be used as curly braces. The curly braces are used to define the body of function and scope of control statements. The opening curly brace ({) indicates starting scope and closing curly brace (}) indic
3 min read
Overloading the Comma Operator
In C++, we can overload the comma operator using Operator Overloading. For Example: For "Send the query X to the server Y and put the result in variable Z", the "and" plays the role of the comma. The comma operator (, ) is used to isolate two or more expressions that are included where only one expression is expected. When the set of expressions ha
5 min read
Comma in C++
Comma (,) in C++ can work in three different contexts: Comma as an operatorComma as a separatorComma operator in place of a semicolon1. Comma as an operator A comma operator in C++ is a binary operator. It evaluates the first operand &amp; discards the result, evaluates the second operand &amp; returns the value as a result. It has the lowest prece
4 min read
Comma operator should be used carefully
In C and C++, comma is the last operator in precedence table. So comma should be carefully used on right side of an assignment expression. For example, one might expect the output as b = 10 in below program. But program prints b = 20 as assignment has higher precedence over comma and the statement "b = 20, a" becomes equivalent to "(b = 20), a". #i
1 min read
Result of comma operator as l-value in C and C++
Using the result of the comma operator as l-value is not valid in C. But in C++, the result of the comma operator can be used as l-value if the right operand of the comma operator is l-value. For example, if we compile the following program as a C++ program, then it works and prints b = 30. And if we compile the same program as a C program, then it
1 min read
Minimal product subsequence where adjacent elements are separated by a maximum distance of K
Given an array arr[] and an integer K, the task is to find out the minimum product of a subsequence where adjacent elements of the subsequence are separated by a maximum distance of K.Note: The subsequence should include the first and the last element of the array. Examples: Input: arr[] = { 1, 2, 3, 4 }, K = 2 Output: 8 The first element in the su
10 min read
Print Triangle separated pattern
Given a number N, the task is to print the triangle-separated pattern. Triangle Separated Pattern: Pattern in which four triangles (left, down, right, up) are separated by forward and backward slash, see this below: \*****/ *\***/* **\*/** ***/*** **/*\** */***\* /*****\ Note: N should be an odd number and the value of N should be more than 4.Examp
6 min read
Count number of islands where every island is row-wise and column-wise separated
Given a rectangular matrix which has only two possible values 'X' and 'O'. The values 'X' always appear in form of rectangular islands and these islands are always row-wise and column-wise separated by at least one line of 'O's. Note that islands can only be diagonally adjacent. Count the number of islands in the given matrix. Examples: mat[M][N] =
14 min read
How to Ask User Input Until Correct Input is Received?
User input is a common source of errors in C++ programs so it’s important to validate user input to make the program more reliable. In this article, we will discuss how to ask the user for input until valid input is received in our C++ program. For Example, Input: asdf Output: Incorrect Input. Please Enter Valid Input.User Input ValidationThe easie
2 min read
Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
How to Take Multiple Line String Input in C++?
In C++, taking string input is a common practice but the cin is only able to read the input text till whitespace. In this article, we will discuss how to read the multiple line of text input in C++. For Example, Input:Enter Your Text: This is amultiline text.Output:You Have Entered:This is amultiline text.Reading Multiple Line String Input in C++ T
2 min read
How to Take Long String Input With Spaces in C++?
In C++, we often take long strings with a lot of characters as inputs with spaces but if we use cin then our input gets terminated as soon as whitespace is encountered. In this article, we will discuss how to take long strings with spaces as input in C++. Take Long String Input With Spaces in C++To take a long string input with whitespace we can us
2 min read
How to read or input a string?
In this article, we are going to learn how to print or output a string using different languages. Strings are considered a data type in general and are typically represented as arrays of bytes (or words) that store a sequence of characters. Strings are defined as an array of characters.  Topics: How to Read or Input a String in C Scanf() How to Rea
3 min read
Program to check if input is an integer or a string
Write a function to check whether a given input is an integer or a string. Definition of an integer : Every element should be a valid digit, i.e '0-9'. Definition of a string : Any one element should be an invalid digit, i.e any symbol other than '0-9'. Examples: Input : 127Output : IntegerExplanation : All digits are in the range '0-9'.Input : 199
15+ min read
Generate two output strings depending upon occurrence of character in input string.
Given an input string str[], generate two output strings. One of which consists of those character which occurs only once in input string and second which consists of multi-time occurring characters. Output strings must be sorted.Examples: Input : str[] = "geeksforgeeks"Output : String with characters occurring once:forString with characters occurr
7 min read
Count characters of a string which when removed individually makes the string equal to another string
Given two strings A and B of size N and M respectively, the task is to count characters of the string A, which when removed individually makes both the strings equal. If there exists several such characters, then print their respective positions. Otherwise, print "-1". Examples: Input: A = "abaac", B = "abac"Output: 2 3 4Explanation: Following remo
8 min read
Generate string by incrementing character of given string by number present at corresponding index of second string
Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices. Examples: Input: S = "sun", N = "966"Output: bat Input: S = "apple", N = "12580"Output: brute Approach: The idea is to traverse the string S[] from left to right. Get the ASCII value of string N[] and add it to t
4 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
Check input character is alphabet, digit or special character
All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it's Alphabet, Number or Special character.ASCII value ranges- For capital alphabets 65 - 90For small alphabets 97 - 122For digits 48 - 57 Examples : Input : 8 Output : Digit Input : E Output : Alphabet C/C++ Code // CPP pro
3 min read
Program to build DFA that starts and end with 'a' from input (a, b)
DFA (Deterministic Finite Automaton or Acceptor) is a finite state machine that accepts or rejects strings of symbols. DFA accepts the string if it reaches the final state and rejects otherwise. Now the problem is, provided a string as input character by character and we have to check whether the string starts and ends with 'a'. We can only store t
8 min read
Input an integer array without spaces in C
How to input a large number (a number that cannot be stored even in long long int) without spaces? We need this large number in an integer array such that every array element stores a single digit. Input : 10000000000000000000000000000000000000000000000 We need to read it in an arr[] = {1, 0, 0...., 0} In C scanf(), we can specify count of digits t
2 min read
Find the maximum sum (a+b) for a given input integer N satisfying the given condition
Given an integer N, the task is to find the largest sum (a + b) {1 ? a ? N, 1 ? b ? N} such that a * b/(a + b) is an integer (i.e a + b divides a * b) and a != b. Examples: Input: N = 10 Output: 9 Explanation: The numbers a = 3 and b = 6 leads to sum = 9 also 6 * 3 = 18 which is divisible by 6 + 3 = 9 Input: N = 20 Output: 27 Naive Approach: The id
11 min read
Implementing DFA for no runs of length less than 4 for input (a,b)
DFA or Deterministic Finite Automata is a finite state machine, in which on every input alphabet a transition is done from one state to another state according to set of defined rules as per the need of string acceptance.In this particular problem, runs of length is the factor to think about.The input alphabets are {a, b}. No runs of length less th
15 min read
Construct a Matrix N x N with first N^2 natural numbers for an input N
Given an integer N, the task is to construct a matrix M[][] of size N x N with numbers in the range [1, N^2] with the following conditions : The elements of the matrix M should be an integer between 1 and N^2.All elements of the matrix M are pairwise distinct.For each square submatrix containing cells in row r through r+a and in columns c through c
6 min read
Simple Input/Output Program in MATLAB
Let us see how to input and output data in MATLAB. input() Syntax : input(PROMPT, "s") Parameters : PROMPT : text prompted "s" : optional, to input a string Returns : the data entered The input() function is used to input data in MATLAB. Example : % entering an integer input(&quot;Enter an integer : &quot;) % entering a string input(&quot;Enter a s
1 min read
Cascading of Input/Output Operators in C++
Prerequisite: Operator Overloading in C++, Types of Operator Overloading When an object calls an operator function by passing an argument and the returned value of the operator function calls the next operator function in the same expression, it is called as cascading of operators. Below are the examples for illustration of Cascading Of Operations:
5 min read
Article Tags :
Practice Tags :