How can I read from an std::istream (using operator>>)?
-
19-09-2019 - |
Question
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'
Solution
Operator >> modifies stream, so don't pass by const, just a reference.
OTHER TIPS
Use a non-const reference:
void foo(std::istream& in) {
std::string tmp;
while(in >> tmp) {
std::cout << tmp;
}
}
You're doing that the right way. Are you sure you included all the headers you need? (<string>
and <iostream>
)?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow