2011-12-23 69 views
-3

这是我之前的问题的后续。将字符数组分割成字符串

Parsing file names from a character array

答案是相关的,但我仍然有麻烦。当字符串被拆分时,我似乎无法让它们正确地输出到我的错误日志中,不管是字符串还是cstring,说实话,我不完全理解他的答案是如何工作的。那么,是否有人对绅士提供的答案有了进一步的解释。我如何将字符数组分成更多的字符串,而不是全部写出来。这是答案。

std::istringstream iss(the_array); 
std::string f1, f2, f3, f4; 
iss >> f1 >> f2 >> f3 >> f4; 

想象一下,我有30个不同的字符串。当然,我不能写f1,f2 .... f30。

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

+6

如果您需要说明,请对答案进行评论。 –

+2

也请停止签署帖子 –

+0

@ TomalakGeret'kal签名帖? –

回答

3

你甚至可以避免明确的循环,并尝试一种现代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,...),例如,如果需要的话,你可以通过向量的索引来引用它们。

+0

+1这比我的建议好。 – hmjd