Home >Backend Development >C++ >Can C 's `cin` Use Custom Delimiters?

Can C 's `cin` Use Custom Delimiters?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 16:11:11477browse

Can C  's `cin` Use Custom Delimiters?

Custom Delimiters for C 's cin

Problem:

When using cin after redirecting it to a file stream (via cin.rdbuf(inF.rdbug())), it reads until reaching a white space character. Is it possible to use an alternative delimiter?

Answer:

Yes, it is possible to change the inter-word delimiter for cin (or any other std::istream) using std::ios_base::imbue and a custom ctype facet.

A custom facet that treats colons (:) and newlines as whitespace characters can be used to read files like /etc/passwd, where fields are separated by colons.

#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() {
  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";
  }
}

By applying this custom facet to the input stream, cin will now interpret colons and newlines as word delimiters, allowing for the separation of fields in files like /etc/passwd.

The above is the detailed content of Can C 's `cin` Use Custom Delimiters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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