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'
From stackoverflow
-
You're doing that the right way. Are you sure you included all the headers you need? (
<string>
and<iostream>
)?: Yes,and are included. Tyler McHenry : 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. -
Operator >> modifies stream, so don't pass by const, just a reference.
: Thanks! Surprising that reading from the stream should modify it, but presumably a position pointer gets advanced by reading.Tyler McHenry : 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. -
Use a non-const reference:
void foo(std::istream& in) { std::string tmp; while(in >> tmp) { std::cout << tmp; } }
0 comments:
Post a Comment