Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing the delimiter for cin (c++)

I've redirected "cin" to read from a file stream cin.rdbug(inF.rdbug()) When I use the extraction operator it reads until it reaches a white space character.

Is it possible to use another delimiter? I went through the api in cplusplus.com, but didn't find anything.

like image 484
yotamoo Avatar asked Sep 05 '11 00:09

yotamoo


People also ask

How do I change my delimiter in CPP?

It is possible to change the inter-word delimiter for cin or any other std::istream , using std::ios_base::imbue to add a custom ctype facet . If you are reading a file in the style of /etc/passwd, the following program will read each : -delimited word separately.

What is delimiter C++?

A delimiter is a unique character or series of characters that indicates the beginning or end of a specific statement, string or function body set.

Does CIN work in c?

The "c" in C++ cin refers to "character" and "in" means "input". Thus, cin means "character input". The C++ cin object belongs to the istream class. It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source.

Does CIN take newline?

In the line “cin >> c” we input the letter 'Z' into variable c. However, the newline when we hit the carriage return is left in the input stream. If we use another cin, this newline is considered whitespace and is ignored. However, if we use getline, this is not ignored.


2 Answers

It is possible to change the inter-word delimiter for cin or any other std::istream, using std::ios_base::imbue to add a custom ctype facet.

If you are reading a file in the style of /etc/passwd, the following program will read each :-delimited word separately.

#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";   } } 
like image 190
Robᵩ Avatar answered Sep 21 '22 03:09

Robᵩ


For strings, you can use the std::getline overloads to read using a different delimiter.

For number extraction, the delimiter isn't really "whitespace" to begin with, but any character invalid in a number.

like image 28
Ben Voigt Avatar answered Sep 21 '22 03:09

Ben Voigt