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

Can C 's `cin` Use Custom Delimiters?

Barbara Streisand
Release: 2024-12-18 16:11:11
Original
492 people have browsed it

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

#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";

  }

}

Copy after login

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!

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