Home >Backend Development >C++ >How Can I Change the Delimiter for `cin` Input in C ?

How Can I Change the Delimiter for `cin` Input in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 16:39:12830browse

How Can I Change the Delimiter for `cin` Input in C  ?

Modifying the Delimiter for 'cin' Input in C

When working with input streams in C , it's common to use 'cin' to read user input. By default, 'cin' treats whitespace characters as delimiters, separating words or tokens. What if you need to use a different delimiter?

While the C Standard Library API doesn't explicitly provide a method to change the delimiter for 'cin,' it is possible to achieve this using the 'std::ios_base::imbue' function.

'std::ios_base::imbue' allows you to add a custom 'ctype' facet to the input stream. Ctype facets define the character classification behavior for a given locale.

Here's an example that demonstrates how to change the delimiter to the colon (':') character:

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

In this example, a custom 'ctype' facet, 'colon_is_space,' is created. This facet classifies the colon (':') and newline ('n') characters as spaces.

By imbuing the input stream with a locale using this custom facet, we effectively change the delimiter for 'cin' to the colon. As a result, when reading input using the extraction operator (>>), it will treat the colon as a separator.

This technique can be used to handle input formats that use non-whitespace characters as delimiters.

The above is the detailed content of How Can I Change the Delimiter for `cin` Input in C ?. 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