-3

My problem sounds like this: I have as a input a huge string with numbers separated by whitespaces. I need to split this string and put the components in a vector and then to use its components. (then to transform to integers bla bla...).

I searched here for this but I did not understand some things entirely, so please a bit of explanation.

Also another question: why the following return one more "Substring: " in the end?

int main()
{
    string s("10 20 30 50 2000");
    istringstream iss(s);

    while (iss)
    {
        string sub;
        iss >> sub;
        cout << "Substring: " << sub << endl;
    }
    system("pause");
    return 0;
}
Elly D
  • 1
  • 1

3 Answers3

2

why the following return one more "Substring: " in the end?

Because your loop is broken; you're checking the stream state before reading from it. It's the same problem as described under:

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

First count the amount of whitespaces like this:

int i = counter;

for( size_t i = 0; i < s.size(); ++i )
{
    if( ' ' == s[i] )
    {
         ++counter;
    }
}

After that you have to substring in another for loop the string s.

Herlex
  • 43
  • 9
0

Try the following approach

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>

int main()
{
    std::string s( "10 20 30 50 2000" );

    std::istringstream is( s );

    std::vector<std::string> v( ( std::istream_iterator<std::string>( is ) ),
                                std::istream_iterator<std::string>() );

    for ( const std::string &t : v ) std::cout << t << std::endl;                                

    return 0;
}

The output is

10
20
30
50
2000

You could initially define the vector as having type std::vector<int> and in the vector initialization use iterator std::istream_iterator<int>.

As for your second question then before outputing a string you have to check whether it was read. So the correct loop will look like

string sub;

while ( iss >> sub )
{
    cout << "Substring: " << sub << endl;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335