Home >Backend Development >C++ >How Can I Customize the Delimiter for Input Streams in C ?
Customizing the Delimiter for Input Streams in C
When reading input from a stream using the extraction operator (cin), the default behavior is to read until a whitespace character is encountered. However, in certain scenarios, it may be necessary to use a custom delimiter.
Changing the Delimiter for cin
The standard library provides a way to modify the inter-word delimiter for input streams, such as cin. This can be achieved using the imbue method of std::ios_base to add a custom character type facet called ctype.
Example: Using a Colon as a Delimiter
For instance, suppose you have a file formatted like /etc/passwd, where each field is separated by a colon (:) character. To read each field separately using a custom colon-based delimiter, you can use the following code:
#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 named colon_is_space is created, which treats the colon character (:) and the newline character (n) as whitespace. By imbuing the input stream cin with this custom locale, the extraction operator (>>) will read each field separated by a colon.
The above is the detailed content of How Can I Customize the Delimiter for Input Streams in C ?. For more information, please follow other related articles on the PHP Chinese website!