Home >Backend Development >C++ >How Can I Customize Input Stream Delimiters in C ?
Customizing Input Stream Delimiters in C
Input streams, such as the standard input stream std::cin, use whitespace characters as delimiters by default. However, what if you need to use an alternative character as the delimiter?
Unfortunately, the C standard library does not provide a straightforward way to change the delimiter for std::cin. However, there is a workaround using the std::ios_base::imbue function to add a custom ctype facet.
The code below demonstrates how to change the delimiter for std::cin to the colon character, effectively reading delimited words in the style of /etc/passwd.
#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() { std::cin.imbue(std::locale(std::cin.getloc(), new colon_is_space)); std::string word; while (std::cin >> word) { std::cout << word << "\n"; } }
In this code, the colon_is_space class is defined as a custom ctype facet that identifies the colon (':' ) and newline ('n' ) characters as space characters. By imbuing this facet into std::cin, we effectively extend the recognition of whitespace characters to include the colon.
As a result, when you use the std::cin >> operator, it will read words delimited by colons. This allows you to easily parse data files that follow a colon-separated format.
The above is the detailed content of How Can I Customize Input Stream Delimiters in C ?. For more information, please follow other related articles on the PHP Chinese website!