-1

I have a function that reads a text file as input and stores the data in a vector.

It works, as long as the text file doesn't contain any extra new lines or white space.

Here is the code I currently have:

std::ifstream dataStream;

dataStream.open(inputFileName, std::ios_base::in);
    
std::string pushThis;
while(dataStream >> pushThis){

    dataVector.push_back(pushThis);

}

For example:

safe mace
bait mate

The above works as an input text file.

This does not work:

safe mace
bait mate


Is there any way to stop the stream once you reach the final character in the file, while still maintaining separation via white space between words in order to add them to something like a vector, stack, whatever?

i.e. a vector would contain ['safe', 'mace', 'bait', 'mate']

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • related: https://stackoverflow.com/a/10376445/4123703 – Louis Go Aug 27 '20 at 01:07
  • 1
    `dataStream >> pushThis` will skip all whitespace for you with no further help unless you've done things to the stream that you aren't showing. In other words, I don't see the problem. You should be getting exactly what you want already. – user4581301 Aug 27 '20 at 01:27
  • 1
    Agreed. After `operator>>` has read the last word (`mate`), the next call to `operator>>` will discard the remaining whitespace (which includes line breaks) until EOF is reached, putting the stream into a state that breaks the loop. Only the 4 words successfully read (`safe` `mace` `bait` `mate`) will have been pushed into the vector. – Remy Lebeau Aug 27 '20 at 01:30
  • I think we're misinterpreting what you want and need a better problem description complete with [mre], input (already got that, thanks for that), desired output for the input (which I think you have also provided), and the output you are currently getting. – user4581301 Aug 27 '20 at 01:35

1 Answers1

0

Answer:

The problem came from having two streams, one using !dataStream.eof() and the other using dataStream >> pushThis.

Fixed so that both use dataStream >> pushThis.

For future reference for myself and others who may find this:

Don't use eof() unless you want to grab the ending bit(s) of a file (whitespace inclusive).

Miguel
  • 2,130
  • 1
  • 11
  • 26
  • 1
    Related: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons – Jerry Jeremiah Aug 27 '20 at 02:11