请解释这段代码

fro*_*eas -4 c++

所以我一直试图在C++中拆分一个字符串并将内容转储到一个向量中.我找到了问题的答案,所以我复制了解决方案并开始使用它来理解它,但它似乎仍然非常神秘.我有以下代码片段,它是我制作和复制材料的混合物.我已经评论了我理解其目的的每一行.有人可以填写剩余的评论(基本上解释他们做了什么).我想完全理解这是如何解决的.

ifstream inputfile; //declare file
inputfile.open("inputfile.txt"); //open file for input
string m; //declare string
getline(inputfile, m); //take first line from file and insert into string

std::stringstream ss(m);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

while(true) //delay the cmd applet from closing
{
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 11

免责声明:真正的代码不应该包含我即将使用的注释程度.(它也不应该是如此被狗狗化身.)

我添加了一个函数体和必要的标题.

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

int main()
{
   // Construct a file stream object
   ifstream inputfile;

   // Open a file
   inputfile.open("inputfile.txt");

   // Construct a string object
   string m;

   // Read first line of file into the string
   getline(inputfile, m);



   // Copy the string into a stringstream so that we can
   // make use of iostreams' formatting abilities
   std::stringstream ss(m);

   // Construct an iterator pair. One is set to the start
   // of the stringstream; the other is "singular", i.e.
   // default-constructed, and isn't set anywhere. This
   // is sort of equivalent to the "null character" you
   // look for in C-style strings
   std::istream_iterator<std::string> begin(ss);
   std::istream_iterator<std::string> end;

   // Construct a vector by iterating through the text
   // in the stringstream; by default, this extracts space-
   // delimited tokens one at a time. The result is a vector
   // of single words
   std::vector<std::string> vstrings(begin, end);

   // Again using iterators (albeit un-named ones, obtained
   // with .begin() and .end()), stream the contents of the
   // vector to STDOUT. Equivalent to looping through `vstrings`
   // and doing `std::cout << *it << "\n"` for each one
   std::copy(
      vstrings.begin(),
      vstrings.end(),
      std::ostream_iterator<std::string>(std::cout, "\n")
   );

   // Blocks the application until it is forcibly terminated.
   // Used because Windows, by default, under some circumstances,
   // will close your terminal after the process ends, before you 
   // can read its output. However: THIS IS NOT YOUR PROGRAM'S
   // JOB! Configure your terminal instead.
   while (true) {}
}
Run Code Online (Sandbox Code Playgroud)

可以这么说,这不是打印到控制台,换行符分隔的最佳方式,每个令牌都可以在磁盘上的文本文件的第一行找到.请不要从互联网上逐字复制代码并期望红海分开.

  • 此外,while(true){}循环是房间加热器.修复您的终端,或至少在循环中进行睡眠调用. (2认同)
  • +1不是一个只是一个评论者,需要时间来解释. (2认同)