你甚至可以避免明确的循环,并尝试一种现代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,...),例如,如果需要的话,你可以通过向量的索引来引用它们。
来源
2011-12-23 13:55:34
mrm
如果您需要说明,请对答案进行评论。 –
也请停止签署帖子 –
@ TomalakGeret'kal签名帖? –