Home >Backend Development >C++ >How Can I Change the Delimiter for `cin` Input in C ?
When working with input streams in C , it's common to use 'cin' to read user input. By default, 'cin' treats whitespace characters as delimiters, separating words or tokens. What if you need to use a different delimiter?
While the C Standard Library API doesn't explicitly provide a method to change the delimiter for 'cin,' it is possible to achieve this using the 'std::ios_base::imbue' function.
'std::ios_base::imbue' allows you to add a custom 'ctype' facet to the input stream. Ctype facets define the character classification behavior for a given locale.
Here's an example that demonstrates how to change the delimiter to the colon (':') character:
#include <locale> #include <iostream> struct colon_is_space : std::ctype<char> { colon_is_space() : std::ctype<char>(get_table()) {} static mask const* get_table() { static mask rc[table_size]; rc[':'] = std::ctype_base::space; rc['\n'] = std::ctype_base::space; return &rc[0]; } }; int main() { using std::string; using std::cin; using std::locale; cin.imbue(locale(cin.getloc(), new colon_is_space)); string word; while(cin >> word) { std::cout << word << "\n"; } }
In this example, a custom 'ctype' facet, 'colon_is_space,' is created. This facet classifies the colon (':') and newline ('n') characters as spaces.
By imbuing the input stream with a locale using this custom facet, we effectively change the delimiter for 'cin' to the colon. As a result, when reading input using the extraction operator (>>), it will treat the colon as a separator.
This technique can be used to handle input formats that use non-whitespace characters as delimiters.
The above is the detailed content of How Can I Change the Delimiter for `cin` Input in C ?. For more information, please follow other related articles on the PHP Chinese website!