C++ std::ifstream read to string delimiters

12,789

Solution 1

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>

Solution 2

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.)

Share:
12,789
kravemir
Author by

kravemir

Just a software developer,..

Updated on June 24, 2022

Comments

  • kravemir
    kravemir almost 2 years

    When using:

    string s;
    cin >> s;
    

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