Frank
Frank

Reputation: 66214

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

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'

Upvotes: 2

Views: 1802

Answers (3)

Tyler McHenry
Tyler McHenry

Reputation: 76710

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

Upvotes: 1

John Millikin
John Millikin

Reputation: 200846

Use a non-const reference:

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

Upvotes: 4

Eugene
Eugene

Reputation: 7258

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

Upvotes: 10

Related Questions