-2

I am currently having trouble converting my thoughts to code. Essentially, I am being tasked with reading lines from a text file. Because I will be accessing individual words from each line, I believe I need to store each line as a vector with each element of the vector being a word from the line. The words from each line will have to be accessed before moving onto the next line in the file. I understand I will probably use getline and stringstream, but I am stuck as to how to store each line from the getline as a vector of individual words.

For example, if I have the following lines in a text file:

This is the first line of the text file.
This is the second line of the text file.

I should be able to extract the words "This" and "first" from the first line and the words "This" and "second" from the second line. I do not need the extracted words from the first line when I move onto the second line.

  • 1
    Although you might have "trouble converting ... thoughts to code", you seem to have no trouble converting them to words. So take those words, and rearrange them in short, logical sentences. Then, [schedule an appointment with your rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging) to review your proposed plan of action. When your rubber duck approves your proposed plan of action, simply take what you've written down and convert it directly to C++. Can you try doing that? Otherwise, this is too broad, and Stackoverflow is for ***specific questions on technical topics***. – Sam Varshavchik Apr 16 '21 at 02:07
  • **Repeat Question** You can find answer here [how-do-i-iterate-over-the-words-of-a-string](https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string/237280#237280) – liangzelang Apr 16 '21 at 02:08
  • Suggest reading line into a string with `getline()` and then creating a `stringstream()` from the line and then extracting words from the stringstream with `>>`. Many examples creating stringstream from a line on this site. – David C. Rankin Apr 16 '21 at 03:08

1 Answers1

0
ifstream textFile("stack.txt"); // reads the textfile 
string sentences; 
vector<string> data; //initializing a vector 

for(int i=0;i<9;i++)
{
    for(int j=0;j<2;j++)
    {
            while(textFile >> sentences)
            {
            data.push_back(sentences); 
            }

    }

}

This stores all of the words in your textfile into a single vector.

output on console of textfile