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++
// C++ program to take long string input with spaces. #include <iostream> #include <string> using namespace std; int main() { // prompt user to enter string cout << "Enter long string with spaces: " ; // declare a string to store the user input string usr_str; // Use getline() to take input with spaces getline(cin, usr_str); // Display the input 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
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++.