How to Take std::cin Input with Spaces?
Last Updated :
01 Mar, 2024
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 the std::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++
#include <iostream>
#include <locale> // to work with locales
#include <string>
using namespace std;
struct changeDelimiter : ctype< char > {
changeDelimiter()
: ctype< char >(
createTable())
{
}
static mask const * createTable()
{
static mask
rc[table_size];
rc[ '\n' ]
= ctype_base::space;
return rc;
}
};
int main()
{
cin.imbue(locale(cin.getloc(), new changeDelimiter));
cout << "Enter Input with Spaces: " << endl;
string inputString;
cin >> inputString;
cout << "Input Entered: " << inputString << endl;
}
|
Output
Enter Input with Spaces:
Hey! Geek Welcome to GfG
Input Entered: Hey! Geek Welcome to GfG
Share your thoughts in the comments
Please Login to comment...