kravemir
kravemir

Reputation: 11026

C++ std::ifstream read to string delimiters

When using:

string s;
cin >> s;

Which characters can string contain and which characters will stop the reading to string.

Upvotes: 3

Views: 13399

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361692

std::ctype_base::space is the delimiter for std::istream which makes it stop reading further character from the source.

std::ctype_base::space refers to whitespace and newline. That means, s can contain any character except whitespace and newline, when reading using cin>>s.

If you want to read complete line containing whitespaces as well, then you can use getline() function which uses newline as delimiter. There also exists its overloaded function, which you can use if you want to provide your own delimiter. See it's documentation for further detail.


You can also use customized locale which you can set to std::istream. Your customized locale can define a set of characters to be treated as delimiter by std::istream. You can see one such example here (see my solution):

Right way to split an std::string into a vector<string>

Upvotes: 10

James Kanze
James Kanze

Reputation: 154017

The delimiter is any character ch for which std::isspace( ch, std::sin.getlocale() ) returns true. In other words, whatever the imbued locale considers "white space". (Although I would consider it somewhat abuse, I've known programmers to create special locales, which consider e.g. , white space, and use >> to read a comma separated list.)

Upvotes: 3

Related Questions