-5

I want to get words from a string (like this: "My name is Jonathan") one by one, and save each word into an elemnt on a list. I want to do it extremelly simple, without any vectors etc. For example

I take one word from a string and save it into an element The same Until end of string.

Wojtek Smol
  • 57
  • 1
  • 2
  • 1
    It's hard to do both "on a list" and "without any vectors etc" as a list usually qualifies as "vectors etc". Could you be more specific? – molbdnilo Jan 24 '16 at 20:02
  • 1
    Using e.g. [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) (or other standard [containers](http://en.cppreference.com/w/cpp/container)) *is* the simple way. Using standard containers, [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string), [streams](http://en.cppreference.com/w/cpp/io) and [algorithms](http://en.cppreference.com/w/cpp/algorithm) and [iterator helper functions](http://en.cppreference.com/w/cpp/iterator) it could be accomplished with only four lines of C++ code, where three lines are variable declarations. – Some programmer dude Jan 24 '16 at 20:02

1 Answers1

3

You can do this the following way

#include <string>
#include <list>
#include <sstream>
#include <iterator>

//...

std::istringstream is( "My name is Jonathan" );

std::list<std::string> lst( ( std::istream_iterator<std::string>( is ) ),
                            std::istream_iterator<std::string>() );

Here is a demonstrative program

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

int main()
{    
    std::istringstream is( "My name is Jonathan" );

    std::list<std::string> lst( ( std::istream_iterator<std::string>( is ) ),
                                std::istream_iterator<std::string>() );

    for ( const std::string &s : lst ) std::cout << s << ' ';
    std::cout << std::endl;

    return 0;
}            

Its output is

My name is Jonathan 

If you want to apply this task to your own list then you can use the following approach

std::istringstream is( "My name is Jonathan" );
std::string word;

while ( is >> word )
{
    // append your list with the word
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • You'll also want to check out [`std::istreambuf_iterator`](http://en.cppreference.com/w/cpp/iterator/istreambuf_iterator) if you ever want to extract char by char. – Brian Rodriguez Jan 25 '16 at 00:10