0

I have the following string "0 1 2 3 4 "(There is a space at the end of the string). Which i would like to split and add to a vector of string. When i use a loop and a stringstream, the program loops itself into a infinity loop with the last number 4. It does not want to stop.

How can I split the following and add to a vector of strings at the same time.

Please advcie.

stringstream ss(currentLine);
for(int i=0;i<strlen(currentLine.c_str());i++){
      ss>>strCode;
      strLevel.push_back(strCode);
    }
M.A
  • 1,073
  • 2
  • 15
  • 21
  • 1
    possible duplicate of [Splitting a string in C++](http://stackoverflow.com/questions/236129/splitting-a-string-in-c) – Mat Aug 10 '13 at 10:44

2 Answers2

5
std::ifstream infile(filename.c_str());
std::string line;

if (infile.is_open())
{
    std::cout << "Well done! File opened successfully." << std::endl;

    while (std::getline(infile, line))
    {
        std::istringstream iss(line);
        std::vector<std::string> tokens { std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() };

        for (auto const &token : tokens)
            if (!token.compare("your_value"))
                // Do something....
    }
}

First of all, we read a line just by using std::istringstream iss(line), then we split words according to the whitespaces and store them inside the tokens vector.

Update: thanks to Nawaz for improvement suggestions (see comments).

vdenotaris
  • 13,297
  • 26
  • 81
  • 132
  • 1
    Why use `std::copy`? You could use the constructor itself: `std::vector tokens{std::istream_iterator(iss),std::istream_iterator()};` No need to use copy! – Nawaz Aug 10 '13 at 11:01
  • See this [demo](http://coliru.stacked-crooked.com/view?id=0d39f0a4882d46d8387c4c5a327a4b71-542192d2d8aca3c820c7acc656fa0c68) which illustrates my previous comment. – Nawaz Aug 10 '13 at 11:06
  • You're right. I edited the code following your suggestion. Thank you! – vdenotaris Aug 10 '13 at 11:11
  • 1
    You could use ranged-based `for` loop instead of index-based `for`. `for(auto const & token : tokens)` is clean and concise, unless you need the index (which is not that often). – Nawaz Aug 10 '13 at 11:13
  • Even if you use index-based `for` loop, there is no reason to use `at()` member inside the loop. See this : [vector.at(x) vs. vector\[x\]](http://stackoverflow.com/questions/11172144/why-is-using-vector-atx-better-than-vectorx-in-c) – Nawaz Aug 10 '13 at 11:15
4
stringstream ss(currentLine);
while ( ss >> strCode )
    strLevel.push_back(strCode);

That should be enough.

Nawaz
  • 353,942
  • 115
  • 666
  • 851