请解释这段代码
Please Explain This Piece of Code
所以我一直试图在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
{
}
免责声明:真正的代码不应该包含我将要使用的注释。(它也不应该如此固执的神秘。)
我已经添加了一个函数体和必要的头文件。
#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) {}
}
可以这么说,不是打印到控制台的最佳方式,以换行符分隔,在磁盘上的文本文件的第一行找到每个标记。请不要一字不差地从互联网上复制代码,并期望红海分开。
相关文章:
- 在java中解决这段代码时面临循环中的问题
- 修改 VS Code 中的默认C++代码段
- 我是如何在这段代码中出现分段错误的
- 我不明白这段代码是如何对这个pythonlist()进行排序的,也不明白如何用C++中的向量来重现它
- 为什么这段代码不起作用,我该如何解决?
- 为什么这段代码给我错误? 有没有自错?
- 有人可以解释一下这段代码如何能够反转字符串
- 可能我知道为什么这段代码没有给出任何输出吗?
- 这段代码的最后一行在做什么?
- 我不知道为什么这段代码会让核心被转储?
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- 有人可以向我解释一下这段代码的作用吗?
- 存储在哪个内存段(代码/数据段)类(员工)中?
- 为什么这段代码会导致无限循环?
- 为什么代码段会引发浮点异常?
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 如何为一段代码启用 -permissive
- 如何知道用于实现标准代码段的确切数据结构和算法,例如在C++STL中?
- 为什么下面的代码段返回指针指向的值而不是指针的地址?
- 谁能告诉我为什么这段代码没有产生正确的输出?