Setting a string using cin then making the string into a list between spaces

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EthaOrigin
    New Member
    • Dec 2015
    • 1

    Setting a string using cin then making the string into a list between spaces

    So I set up a string like this:

    string input
    cin >> input

    then I want to split that string into a list so that all the words in between spaces are entries in a list.

    So if the string were "I like cats"
    The list would have the first entry be "I" and the second entry would be "like" and so on.

    How do I do this??
  • hpmachining
    New Member
    • Oct 2015
    • 15

    #2
    First off, you won't be able to get a string with spaces using std::cin like that. It will only get the first word. Instead use std::getline. Then one way to to get the individual words is with std::stringstre am, which allows a string to be treated as a stream.
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <vector>
    
    int main(void)
    {
      std::string input;
      std::getline(std::cin, input);
      
      std::stringstream inputStream(input);
      std::vector<std::string> words;
      std::string word; // temporary buffer to hold extracted word
      while (inputStream >> word)
        words.push_back(word);
    
      for (size_t i = 0; i < words.size(); ++i)
        std::cout << words[i] << std::endl;
    
      return 0;
    }
    I used a std::vector for the list, but if you actually want to use std::list, replace
    Code:
    #include <vector>
    with
    Code:
    #include <list>
    Replace
    Code:
    std::vector<std::string> words;
    with
    Code:
    std::list<std::string> words;
    And to iterate the list replace
    Code:
    for (size_t i = 0; i < words.size(); ++i)
        std::cout << words[i] << std::endl;
    with
    Code:
     for (auto it = words.begin(); it != words.end(); ++it)
        std::cout << *it << std::endl;

    Comment

    Working...