Search code examples
c++stringiteratoristream-iterator

C++ compilation error using string and istream_iterator


When trying to compile the following:

#include <string>
#include <iterator>
#include <iostream>
using namespace std;
int main() {
  string s(istream_iterator<char>(cin), istream_iterator<char>());
  return s.size();
}

g++ 4.4.1 gives me:

main.cc: In function ‘int main()’:
main.cc:6: error: request for member ‘size’ in ‘s’, which is of non-class type ‘std::string(std::istream_iterator<char, char, std::char_traits<char>, int>, std::istream_iterator<char, char, std::char_traits<char>, int> (*)())’

According to libstdc++ docs, string has a ctor that takes a begin/end iterator pair. Why do I get this error, then?


Solution

  • You're accidentally declaring a function instead of instantiating a string. Try declaring variables for your istream_iterator objects and then passing those to the std::string constructor.

    And here's a good read that describes exactly your problem: http://www.gotw.ca/gotw/075.htm