How to Take std::cin Input with Spaces?
Last Updated :
01 Mar, 2024
Improve
In C++, std::cin is used to accept the input from the standard input device. By default, the delimiter used by std::cin to separate input is a whitespace. In this article, we will learn how to take std::cin input with spaces in C++.
Example:
Input: Hey! Geek Welcome to GfG //input with spaces
Output: Input Entered: Hey! Geek Welcome to GfG
std::cin Input with Spaces in C++
To take std::cin input with spaces we need to customize the behavior of the standard input stream by treating the newline character ('\n') as a delimiter in place of a space. To achieve this use the below approach:
Approach:
- Define a custom locale facet that modifies the character classification table used by the locale to alter how characters are interpreted by the input stream.
- Inside the custom locale change the classification of the newline character (
'\n'
) to be considered as a space character. - Finally, apply the custom locale by using
cin.imbue()
to set the locale of thestd::cin
with a new locale.
C++ Program to Take std::cin Input with Spaces
The below program demonstrates how we can take std::cin input with spaces in C++.
// C++ program to take std::cin input with spaces
#include <iostream>
#include <locale> // to work with locales
#include <string>
using namespace std;
// Defining a structure that inherits from ctype<char>
struct changeDelimiter : ctype<char> {
// Constructor for changeDelimiter
changeDelimiter()
: ctype<char>(
createTable()) // Initializing the base class
// ctype<char> with a table
{
}
// Static function to create a table with custom
// settings
static mask const* createTable()
{
static mask
rc[table_size]; // Creating a table with the
// size of the character set
rc['\n']
= ctype_base::space; // Set the newline
// character to be treated
// as whitespace
return rc; // Return the modified table
}
};
int main()
{
// Creating a custom locale with the changeDelimiter
// facet
cin.imbue(locale(cin.getloc(), new changeDelimiter));
// prompt the user to enter the input with spaces
cout << "Enter Input with Spaces: " << endl;
string inputString;
// Read input from cin, which has the modified locale
cin >> inputString;
// Print the input string
cout << "Input Entered: " << inputString << endl;
}
Output
Enter Input with Spaces:
Hey! Geek Welcome to GfG
Input Entered: Hey! Geek Welcome to GfG