Home > Backend Development > C++ > How Can I Customize Input Stream Delimiters in C ?

How Can I Customize Input Stream Delimiters in C ?

Patricia Arquette
Release: 2024-12-19 07:34:09
Original
698 people have browsed it

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 &amp;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";
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template