std::wifstream theFileHandle;
std::wstring theData;
theFileHandle.open( theFile.Name() );
theFileHandle >> theData;
theFileHandle.close();
Could anyone tell me why my string (theData) is only getting the first word from the file (theFile) ??? I would like the string to contain all of the text from the file including white spaces and new lines, does anyone have a suggestion for this? Thank you.
PS. I need the data to be preserved perfectly. Thanks.
The reason you’re only getting the first word is that this is precisely how the
>>operator works when applied to strings – it just gets the first whitespace-delimited token from whatever stream you’re reading from, after skipping any leading whitespace.If you want to read the entire contents of the file, you can use the
getlinefunction like this:This loops while more data can be read via
getlineand thus pulls all the data from the file. Sincegetlineskips over newlines, this approach also adds the newlines back in.EDIT: As pointed out by @PigBen, there is a much cleaner way to do this using
rdbuf():This uses the fact that the stream insertion operator is overloaded to take in a stream buffer. The behavior in this case is to read the entire contents of the stream buffer until all of the data has been exhausted, which is exactly the behavior you want.