How to Take Long String Input With Spaces in C++?
Last Updated :
06 Feb, 2024
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 use repeatedly getline() function using which we can read an entire line along with spaces in a single go until the user presses enter which indicates that the input is finished.
C++ Program to Take Long String Input With Spaces
The below example uses a getline() function to read the entire line of input, ensuring that spaces are included.
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter long string with spaces: " ;
string usr_str;
getline(cin, usr_str);
cout << "You entered: " << usr_str << endl;
return 0;
}
|
Output
Enter long string with spaces: Hello, Geeks Welcome to GfG
You entered: Hello, Geeks Welcome to GfG
Share your thoughts in the comments
Please Login to comment...