从一个文本文件读取到一个向量中——换行符被描述为一个空向量,它给出了什么



C++引物有以下描述和示例(第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;

我不明白的是,当从文本文件甚至用户输入中读取时,换行符n如何被解释为空向量?

我设置了一个循环,将输入读取为矢量,如下所示,这是书中描述的方法:

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

以这种方式接收输入会擦除空白,包括换行符,不是吗?如何解释换行符并将其存储为空向量?为什么书中这样描述它?

本书通过在Windows中的CMD中执行以下操作来描述前几页中的输入重定向:

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

以上是我将如何将文件中的输入读取到程序中。

如果要保留空白,则需要getline()

#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;
}

控制台上的输入:

Paragraph 1
does not stop yet
but stops now

输入,存储一个空行,这将导致!it->empty()失败,从而停止输出循环。

Paragraph 2
will not be output

Ctrl+Z,是EOF(文件结束(字符,后跟输入

最新更新