Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 12th, 2012  |  syntax: None  |  size: 1.29 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Splitting a character array into strings
  2. std::istringstream iss(the_array);
  3. std::string f1, f2, f3, f4;
  4. iss >> f1 >> f2 >> f3 >> f4;
  5.        
  6. #include <iostream>
  7. #include <vector>
  8. #include <algorithm>
  9. #include <string>
  10. #include <sstream>
  11. #include <iterator>
  12.  
  13. int main()
  14. {
  15.    // Your files are here, separated by 3 spaces for example.
  16.    std::string s("picture1.bmp   file2.txt   random.wtf   dance.png");
  17.  
  18.    // The stringstream will do the dirty work and deal with the spaces.
  19.    std::istringstream iss(s);
  20.  
  21.    // Your filenames will be put into this vector.
  22.    std::vector<std::string> v;
  23.  
  24.    // Copy every filename to a vector.
  25.    std::copy(std::istream_iterator<std::string>(iss),
  26.     std::istream_iterator<std::string>(),
  27.     std::back_inserter(v));
  28.  
  29.    // They are now in the vector, print them or do whatever you want with them!
  30.    for(int i = 0; i < v.size(); ++i)
  31.     std::cout << v[i] << "n";
  32. }
  33.        
  34. std::vector<std::string> filenames;
  35. std::string the_array("picture1.bmp   file2.txt   random.wtf   dance.png");
  36. std::istringstream iss(the_array);
  37.  
  38. while (iss.good())
  39. {
  40.     std::string s;
  41.     iss >> s;
  42.     if (s.length() > 0)
  43.     {
  44.         filenames.push_back(s);
  45.     }
  46. }
  47.  
  48. for (std::vector<std::string>::const_iterator i = filenames.begin();
  49.      i != filenames.end();
  50.      i++)
  51. {
  52.     std::cout << *i << "n";
  53. }