How to Take Multiple String Inputs in a Single Line in C++?
Last Updated :
08 Feb, 2024
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++
#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);
cout << "Enter the delimiter: " ;
getline(cin, delimiter);
stringstream ss(input);
string token;
int i = 1;
while (getline(ss, token, delimiter[0])) {
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
Share your thoughts in the comments
Please Login to comment...