-1

I'm taking in string inputs and I need to read in multiple words from one line and push them into a vector. I can't for the life of me figure out how to split the string whenever there's a space character. I know I need to use the getline() function, but I feel like I've tried everything and I'm stuck.

Here's my code so far. I'm aware that the if/else statement are both doing the same thing.

int main(){
    vector<string> vec;
    string str = "";
    string t = "";
    int i = 0;

    while(getline(cin, str){
        if(str != "STOP"){
            if(str[i] == ' '){
                vec.push_back(str);
            }else{
                vec.push_back(str);
            }
        }else{
            cout << vec.size() << endl;
        }
        i += 1;
    }
}

I can't really use any fancy code, just the basic functions

ethanh
  • 23
  • 5
  • String splitting in C++? LOL. Probably the most requested functionality that the standard libraries have yet to provide – smac89 Jan 18 '21 at 00:44
  • This question is a duplicate of https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c and https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string – Pascal Getreuer Jan 18 '21 at 00:46
  • If you have a C++20-compatible compiler, you can use [this answer](https://stackoverflow.com/a/61621475/2089675), which depends on the range library – smac89 Jan 18 '21 at 00:48

1 Answers1

1

You can use getline() to take the input and then use stringstream for splitting the strings. Like:

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

int main(){
    string arr;
    getline(cin, arr);

    stringstream ss(arr);
    string word;

    vector<string> v;
     
    while(ss >> word){
       // your desired strings are in `word` one by one, you can store these strings in a vector
       v.push_back(word);
    }
}

for continuously taking input and processing do this :

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

int main(){
    string arr;
    
    while(getline(cin, arr)){
    
        stringstream ss(arr);
        string word;
    
        vector<string> v;
         
        while(ss >> word){
           // your desired strings are in `word` one by one, you can store these strings in a vector
           //v.push_back(word);
           cout << word << " ";
        }
        cout << "\n";
    }
}
Sahadat Hossain
  • 2,470
  • 2
  • 6
  • 13