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.
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.
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.
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.
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.
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"; } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With