views:

208

answers:

3

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'
+1  A: 

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

Tyler McHenry
Yes, <string> and <iostream> are included.
Eugene is right. I didn't notice the const reference. The reason it complains with this particular error is because there's no version of operator>> that takes a const stream.
Tyler McHenry
+7  A: 

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

Eugene
Thanks! Surprising that reading from the stream should modify it, but presumably a position pointer gets advanced by reading.
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
+1  A: 

Use a non-const reference:

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