简体   繁体   中英

What format of input does this function expect to parse from std::istream?

I am following along the great book C++17 by Example , which introduces C++17 by showcasing a series of mini projects -- very cool.

However, in chapter 2, where a Set is implemented on top of a LinkedList , there is this code:

void Set::read(std::istream& inStream) {
  int size;
  inStream >> size;

  int count = 0;
  while (count < size) {
    double value;
    inStream >> value;
    insert(value);
    ++count;
  }
}
void Set::write(std::ostream& outStream) {
  outStream << "{";

  bool firstValue = true;
  Iterator iterator = first();

  while (iterator.hasNext()) {
    outStream << (firstValue ? "" : ", ") << iterator.getValue();
    firstValue = false;
    iterator.next();
  }

  outStream << "}";
}
int main() {
  Set s, t;

  s.read(std::cin);
  t.read(std::cin);

  std::cout << std::endl << "s = ";
  s.write(std::cout);
  std::cout << std::endl;

  std::cout << std::endl << "t = ";
  t.write(std::cout);
  std::cout << std::endl << std::endl;

  // snip
}

I am fairly new to C++, and I do not know how to run this. Of course, I did some research before asking, but the way I came up with does not produce the expected results:

lambdarookies-MacBook:02-the-set-class lambdarookie$ ./02-the-set-class
1 2 3
3 4 5

s = {2}         // Expected: s = {1, 2, 3}
t = {3, 4, 5}

Now I am wondering:

  • Is this simply not the right way to supply arguments, or
  • it is the right way, and the bug must be elsewhere in the code?

The first number Set::read reads is the size of the set. Then it reads that many numbers, and adds them to the set. The rest of the line is ignored by the current invocation of read , and is picked up by the next one, which is, by coincidence, the size of the next set you are testing with. Therefore, inputting 1 2 3 results in a set of size 1 , with the only elem 2 .

Please note: hasNext is a java-ism, unlike how the usual C++ iterators work. Perhaps you could consider also taking a look at a different manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM