c++ - Save one by one words from string to the list -


i want words string (like this: "my name jonathan") 1 one, , save each word elemnt on list. want extremelly simple, without vectors etc. example

i take 1 word string , save element same until end of string.

you can following way

#include <string> #include <list> #include <sstream> #include <iterator>  //...  std::istringstream is( "my name jonathan" );  std::list<std::string> lst( ( std::istream_iterator<std::string>( ) ),                             std::istream_iterator<std::string>() ); 

here demonstrative program

#include <iostream> #include <string> #include <list> #include <sstream> #include <iterator>  int main() {         std::istringstream is( "my name jonathan" );      std::list<std::string> lst( ( std::istream_iterator<std::string>( ) ),                                 std::istream_iterator<std::string>() );      ( const std::string &s : lst ) std::cout << s << ' ';     std::cout << std::endl;      return 0; }             

its output is

my name jonathan  

if want apply task own list can use following approach

std::istringstream is( "my name jonathan" ); std::string word;  while ( >> word ) {     // append list word } 

Comments