How to Take Multiple String Inputs in a Single Line in C++?
In C++, strings are used to store textual data. While working with user input, we often may need to take multiple string inputs in a single line only. In this article, we will learn how to take multiple string inputs in a single line.
Example
Input: Hi,Geek,Welcome,to,GfG delimiter = ',' Output: String 1: Hi String 2: Geek String 3: Welcome String 4: to String 5: GfG
Take Multiple String Inputs in C++
To take multiple string inputs in a single line, we can use the std::getline() function with a user-defined delimiter (like space, semicolon, comma, etc) that indicates the end of one string. We can then tokenize that string using the stringstream and geline() function.
C++ Program to Take Multiple String Inputs
C++
// C++ program to take multiple string inputs in a single // line. #include <iostream> #include <sstream> #include <string> using namespace std; int main() { string input; string delimiter; cout << "Enter multiple strings separated by a custom " "delimiter: " ; getline(cin, input); // Prompt the user to enter a custom delimiter cout << "Enter the delimiter: " ; getline(cin, delimiter); // Using stringstream to tokenize the input based on the // custom delimiter stringstream ss(input); string token; int i = 1; while (getline(ss, token, delimiter[0])) { // Process each string token cout << "String " << i << " " << token << endl; i++; } return 0; } |
Output
Enter multiple strings separated by a custom delimiter: Hi,Geek,Welcome,to,GfG Enter the delimiter: , String 1 Hi String 2 Geek String 3 Welcome String 3 to String 4 GfG