Read an ifstream word for word into char*

237 views Asked by At

Just trying a programming test for fun. It stipulates that I should read each word of a file, one by one.

It hints that I might want to use ifstream, but won't let me use std::string, so it looks like I have to use char*

In C I would read line by line & use strok() as I have multiple delimiters (white-space, quotes, brackets, etc).

What the most C++ way to do this - get the words one by one - without using std::string ?

2

There are 2 answers

2
Some programmer dude On BEST ANSWER

First you must make sure that you have memory allocated for your string (this part would be handled automatically by std::string). Then just use the normal input operator >>, as it will separate on whitespace.

Don't forget to free the memory you allocate (also handled automatically by std::string).

Lesson to be learned: Use char pointers for exercises like these, otherwise use std::string.

2
BufferOverflow On

Just read the file into a std::string and then use std::string::c_str ( ) to retrive the nul-terminated C-style string from std::string object.