Search code examples
c++istream

How to use std::istream correctly


I want to do the following:

// I want 'is' to be either opened file or stringstream ...
void ParseTokens(const std::istream &is, std::vector<TokenClass> &vToks)
{
    char ch;
    ...
    is >> ch;
    ...
}

The compiler complains:

error: ambiguous overload for ‘operator>>’ in ‘is >> ch’

What do I need to do to make this work?

[edit]
Just a caveat: operator>> gives formatted output - it loses white-space characters (tabs, newlines, etc). To access all the characters, you need to use get().


Solution

  • Since is >> ch; extracts characters from is, it modifies the stream. Therefore, it can't be const in the function signature, which can cause seemingly irrelevant errors because there's no exact match. Change the function to take a std::istream &.