What's the difference between >> and get()?

L

Lambda

I'd like to load a text file to memory. The code is like:

void load_dict()
{
static const string DICT("D:\\README.txt");

ifstream dict(DICT.c_str(), std::ios::in);

if (!dict)
{
cerr << "can't open input file: " << DICT << endl;
}

vector<unsigned char> raw;
char c;
while (dict.get(c))
{
raw.push_back(c);
}
cout << raw.size() << endl;
}

It says there is 36388 bytes. That's correct.

But if I change the code to 'dict >> c', there is only 29658 bytes.
What's wrong with the >> operator?
I'm developing under Windows to read unix format file.

And if I change the code to:
unsigned char c;
while (dict.get(c)) ...
There is compilation errors.

What can I do if I want to load binary data?
 
E

Eric Johnson

"The "get()" and "getline()" functions treat whitespace characters
exactly like other characters. They are intended for input
operations, where one doesn't make assumptions about the meanings of
the characters read." -- Bjarne Stroustrup _The_C+
+_Programming_Language, 3rd edition, section 21.3.4

On the other hand, ">>" skips whitespace. That's why you see a
smaller size in the vector.

As for unsigned char versus "plain" char, the char data type may be
signed or unsigned. "Plain" char is what you should use.

To read a binary file, open the file stream like this:
ifstream dict(DICT.c_str(), std::ios::in | std::ios::binary);
(Haven't compiled this line, but I think that's right.)

Nicolai Josuttis' _The_C++_Standard_Library_ is another good reference
for this stuff.

Good luck!
 
J

Jerry Coffin

[ ... ]
But if I change the code to 'dict >> c', there is only 29658 bytes.
What's wrong with the >> operator?

Nothing -- but (by design) it skips white space in the input.

If you really want to use it, you can turn that off, but for what you're
doing, it sounds like read() is more suitable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top