在 linux 上使用命令行重定向(wiith <)将文件内容存储在字符串中?

Storing contents of file in string using command line redirection (wiith <) on linux?

本文关键字:文件 字符串 存储 lt linux 命令行 wiith 重定向      更新时间:2023-10-16

如果我以这种方式运行main.cpp:

./main.cpp < file.txt

当我把这个输入存储在字符串的向量中时,同一行的每个字都存储在新行中。如何有效而优雅地将每一整行存储在矢量字符串的一个元素中?例如我希望它是:

Myvector[0]= "this is just a sentence"

不喜欢:

Myvector[0] ="this"
Myvector[1]="is"
Myvector[3]="just" etc

使用std::getline

std::string text_line;
while (std::getline(std::cin, text_line))
{
  my_vector.push_back(text_line);
}

std::getline函数读取直到遇到换行符,将数据存储到字符串中。

之所以使用std::cin,是因为您正在通过管道传输文件中的数据。