std::isspace in the exemple on the std::istream::sentry page

I was running the example code on std::istream::sentry page and I didn't understand why std::isspace on line 17 doesn’t get out of the loop, since on the line 24 the string buffer starts with white space (" (555)2326").

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  // istream::sentry example
#include <iostream>     // std::istream, std::cout
#include <string>       // std::string
#include <sstream>      // std::stringstream
#include <locale>       // std::isspace, std::isdigit

struct Phone {
  std::string digits;
};

// custom extractor for objects of type Phone
std::istream& operator>>(std::istream& is, Phone& tel)
{
    std::istream::sentry s(is);
    if (s) while (is.good()) {
      char c = is.get();
      if (std::isspace(c,is.getloc())) break;
      if (std::isdigit(c,is.getloc())) tel.digits+=c;
    }
    return is;
}

int main () {
  std::stringstream parseme ("   (555)2326");
  Phone myphone;
  parseme >> myphone;
  std::cout << "digits parsed: " << myphone.digits << '\n';
  return 0;
}
The constructor of the sentry object skips initial whitespace unless the skipws flag is unset.
Try putting a space between the digits somewhere and it'll stop there.

You can unset the skipws flag like this:

1
2
3
parseme >> std::noskipws;
// or
parseme.unsetf(parseme.skipws);

https://en.cppreference.com/w/cpp/io/basic_istream/sentry
https://en.cppreference.com/w/cpp/io/manip/skipws
Last edited on
Now it makes sense. Thank you dutch!
Topic archived. No new replies allowed.