C++ 将字符数组拆分为字符串

C++ 将字符数组拆分为字符串,c++,string,split,C++,String,Split,这是我上一个问题的后续问题 答案是相关的,但我仍然有困难。当字符串被拆分时,我似乎无法将它们作为字符串或cstring正确地输出到我的错误日志中,老实说,我不完全理解他的答案是如何工作的。那么,有人对这位先生提供的答案有进一步的解释吗。我如何将字符数组分割成更多的字符串,而不是将它们全部写出来。这就是答案 std::istringstream iss(the_array); std::string f1, f2, f3, f4; iss >> f1 >> f2 >&

这是我上一个问题的后续问题

答案是相关的,但我仍然有困难。当字符串被拆分时,我似乎无法将它们作为字符串或cstring正确地输出到我的错误日志中,老实说,我不完全理解他的答案是如何工作的。那么,有人对这位先生提供的答案有进一步的解释吗。我如何将字符数组分割成更多的字符串,而不是将它们全部写出来。这就是答案

std::istringstream iss(the_array);
std::string f1, f2, f3, f4;
iss >> f1 >> f2 >> f3 >> f4;
假设我有30个不同的字符串。当然,我不会写f1,f2…f30


关于如何做到这一点的任何建议?

< p>你甚至可以避免显式的for循环,并且尝试一种对现代C++更自然的方式。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
#include <iterator>

int main()
{
   // Your files are here, separated by 3 spaces for example.
   std::string s("picture1.bmp   file2.txt   random.wtf   dance.png");

   // The stringstream will do the dirty work and deal with the spaces.
   std::istringstream iss(s);

   // Your filenames will be put into this vector.
   std::vector<std::string> v;

   // Copy every filename to a vector.
   std::copy(std::istream_iterator<std::string>(iss),
    std::istream_iterator<std::string>(),
    std::back_inserter(v));

   // They are now in the vector, print them or do whatever you want with them!
   for(int i = 0; i < v.size(); ++i)
    std::cout << v[i] << "\n";
}

这是处理类似我有30个不同字符串的场景的明显方法。将它们全部存储在某个地方,根据您可能希望对文件名执行的操作,std::vector可能是合适的。通过这种方式,您不需要为每个字符串指定名称f1、f2,…,例如,如果需要,您可以通过向量的索引来引用它们。

如果需要澄清,请对答案进行评论。此外,请停止签名posts@TomalakGeret“kal签名帖?”PladniusBrooks你不需要写感谢之类的东西。或者在你问题的结尾。这就是署名。