26

I am trying to write a function which will detect when I'm almost at the end of a stringstream, but it doesn't seem to work.

Here's some code:

std::string path(1.2.3);
int number;
std::stringstream ss(path);
while (!ss.eof()) {
    if (ss.peek() != '.') {
        ss >> number;
        if (ss.tellg() == path.length()) {
            std::cout << "Last one: " << number;
        } else {
            std::cout << number;
        }
    } else { ss.get(); }
}

I tried using ss.tellg() == path.length(), but that doesn't work. Does somebody have an alternative?

JNevens
  • 11,202
  • 9
  • 46
  • 72

1 Answers1

23

I figured it out..

std::string path(1.2.3);
int number;
std::stringstream ss(path);
while (!ss.eof()) {
    if (ss.peek() != '.') {
        ss >> number;
        if (ss.tellg() == -1) {
            std::cout << "Last one: " << number;
        } else {
            std::cout << number;
        }
    } else { ss.get(); }
}
JNevens
  • 11,202
  • 9
  • 46
  • 72
  • Umm...You never extracted a value into `number`, so why are you trying to print it? – David G Dec 13 '13 at 19:32
  • 4
    It is better to simply do `while (ss)`. EOF is just one of several reasons why you could not read from a stream anymore. – isekaijin Dec 13 '13 at 20:28
  • @EduardoLeón is right. When `ss` is false, it means you cannot read any more. Then call `ss.eof()` to tell whether `end of file` is the reason you cannot read any more. – xuhdev Aug 01 '15 at 23:00
  • 2
    Neither of the suggested termination conditions should be used without understanding what they could return. @pyon using `while(ss)` will result in reading an extra bogus value when it exits. @JNevens `ss.eof()` can be 0 for a number of reasons, so we can't be certain the intended termination is why the loop exits; some discussion [here](http://stackoverflow.com/questions/14615671/whats-the-real-reason-to-not-use-the-eof-bit-as-our-stream-extraction-condition). – BoltzmannBrain Sep 20 '16 at 16:10
  • what about while (ss.peek() != EOF) – Shaobo Zi Mar 10 '17 at 06:53