2

How can I read from an std::istream using operator>>?

I tried the following:

void foo(const std::istream& in) {
  std::string tmp;
  while(in >> tmp) {
     std::cout << tmp;
  }
}

But it gives an error:

error: no match for 'operator>>' in 'in >> tmp'
Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Frank
  • 64,140
  • 93
  • 237
  • 324
  • the istream shouldn't be const for a start. the istream object's state will need to change as a consequence of you pulling data out of it. – jon hanson Aug 19 '09 at 22:39

3 Answers3

10

Operator >> modifies stream, so don't pass by const, just a reference.

Eugene
  • 7,180
  • 1
  • 29
  • 36
  • Thanks! Surprising that reading from the stream should modify it, but presumably a position pointer gets advanced by reading. – Frank Aug 19 '09 at 22:43
  • 2
    It shouldn't be surprising. Reading from an instream now changes what you will read from that same stream later. This is an observable external effect, and therefore should be considered to modify the object, regardless of the internal implementation detail of the position pointer. – Tyler McHenry Aug 19 '09 at 22:50
4

Use a non-const reference:

void foo(std::istream& in) {
  std::string tmp;
  while(in >> tmp) {
     std::cout << tmp;
  }
}
John Millikin
  • 197,344
  • 39
  • 212
  • 226
1

You're doing that the right way. Are you sure you included all the headers you need? (<string> and <iostream>)?

Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166