-2

C++ primer has the following description and example (p. 110):

assume we have a vector<string> named text that holds the
data from a text file. Each element in the vector is either a sentence or an empty
string representing a paragraph break. If we want to print the contents of the first
paragraph from text, we’d write a loop that iterates through text until we
encounter an element that is empty:

for (auto it = text.cbegin(); it != text.cend() && !it->empty(); ++it)
        cout << *it << endl;

What I don't understand is how can a newline character \n be interpreted as an empty vector when reading from a text file or even user input?

I set up a loop to read input into a vector as follows, which is the method described in the book:

vector<string> text;
    string s;
    while (cin >> s)
        text.push_back(s);

Receiving inputs in this manner erases white space including newlines does it not? How would I interpret newlines and store them as empty vectors? Why does the book describe it in this manner?

The book describes input re-direction in the earlier pages by doing the following in CMD in Windows:

cd [PROJECT LOCATION]
PROJECT.EXE <input.txt>output.txt

The above is how I would read input from a file into my program.

Spellbinder2050
  • 644
  • 3
  • 13
  • Your loop doesn't honor the definition of what that loop expects. It expects either *sentences* and empty strings. Your loop builds a list of whitespace (including newlines) separated tokens. You *probably* want a `std::getline` loop, not a formatted string extraction loop. – WhozCraig May 25 '21 at 15:57
  • Yes I understand that's what it expects, but how can I create a loop that reads data into a vector in the manner that it describes because the only input method that involves vectors is the one I wrote above. How can a newline be an empty vector when reading input? – Spellbinder2050 May 25 '21 at 16:07

1 Answers1

1

You need getline() if you want to keep the whitespace:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> text;
    std::string s;
    while (std::getline(std::cin, s))
    {        
        text.push_back(s);
    }

    // output first paragraph
    for (auto it = text.begin(); it != text.end() && !it->empty(); ++it)
        std::cout << *it << std::endl;
}

Input on Console:

Paragraph 1
does not stop yet
but stops now

Enter, storing an empty line, which will later cause !it->empty() to fail and thus the output loop to stop.

Paragraph 2
will not be output

Ctrl+Z, being the EOF (end of file) character followed by Enter, the combination of both which will cause getline() to end.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222