Home >Backend Development >C++ >How Can I Customize Delimiters for Input Streams in C ?
Customizing Delimiters for Input Streams in C
When reading input from a file stream using "cin," the default delimiter for word extraction is whitespace. While this behavior suffices in most cases, scenarios may arise where alternative delimiters are required. This article demonstrates how to change the inter-word delimiter for "cin" using the "std::ios_base::imbue" function.
To illustrate, consider the example of reading a file formatted like "/etc/passwd," where each field is separated by a colon (:). The following C program leverages the "std::ios_base::imbue" function to redefine the colon character as a whitespace delimiter:
#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"; } }
This program, when presented with "/etc/passwd"-formatted input, will successfully read and output each field separated by a colon. The "colon_is_space" structure reassigns the colon character to be treated as a whitespace character, allowing "cin" to treat it as a delimiter.
The above is the detailed content of How Can I Customize Delimiters for Input Streams in C ?. For more information, please follow other related articles on the PHP Chinese website!