Solving an error

Hi,

I'm still quite new at C++ (far past HelloWorld though =D) and having trouble with an error. My goal is to parse a file and I'm having trouble with a helper class. I'll post some of the code, if you need something else please ask, I'm still new to asking questions too.

1
2
3
4
5
6
7
8
9
10
11
#include <sstream>
#include <string>
using namespace std;

class StreamUtil
{
public:
        StreamUtil();
	short ReadShort(istream);
	string ReadCString(istream);
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "StreamUtil.h"

typedef unsigned char byte;

StreamUtil::StreamUtil()
{
}

short StreamUtil::ReadShort(istream is)
{
	const int n = 2;
	byte* buffer = new byte[n];
	for(int i=0;i<n;i++)
	{
		buffer[i]=is.get();
	}

	short result = 0;
	int m = 0;
	for(int i=0;i<n;i++)
	{
		m = buffer[i] & 0xFF;
		m <<= i*8;
		result |= m;
	}

	return result;
}

string StreamUtil::ReadCString(istream is)
{
	stringbuf* scratchfile = new stringbuf;
	int len = is.get();

	if(len == (byte)0xFF) len = ReadShort(is);
	for(int i=0;i<len;i++)
	{
		scratchfile->sputc((char)is.get());
	}

	return scratchfile->str();
}


and the error:

StreamUtil.cpp
c:\program files\microsoft visual studio 9.0\vc\include\istream(846) : error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
with
[
_Elem=char,
_Traits=std::char_traits<char>
]
c:\program files\microsoft visual studio 9.0\vc\include\ios(151) : see declaration of 'std::basic_ios<_Elem,_Traits>::basic_ios'
with
[
_Elem=char,
_Traits=std::char_traits<char>
]
This diagnostic occurred in the compiler generated function 'std::basic_istream<_Elem,_Traits>::basic_istream(const std::basic_istream<_Elem,_Traits> &)'
with
[
_Elem=char,
_Traits=std::char_traits<char>
]

Any suggestions?


Another problem is that I don't like sputc(). I was looking for a c++ equivalent for the java stringbuffer.append(), but I'm finding that not so easy either. Would love suggestions on that too...
Last edited on
Two things.

First, do you mean istream or ifstream?
Second, I believe your compile error is because you are passing istreams by value to your functions, and IIRC istreams are not copyable. You need to pass by reference instead.

ie,

 
void func( istream& is ); // The '&' means reference 

Now that you mention them, I think I should indeed be using ifstream instead.

And about the pass by reference... I know it, I've used it a thousand times, and each time I forget it again. Thanks for the suggestion!
Topic archived. No new replies allowed.