Training/Problem Solving

[C++] 문자열 공백 기준으로 자르기 (string split)

FATKITTY 2022. 1. 1. 20:04
반응형

💥  필.수.암.기  💥

 

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter);

int main() {
    string user_input;
    vector<string> words;

    getline(cin, user_input);
    words = split(user_input, ' ');
    for (int i = 0; i < words.size(); i++) {
        cout << words[i] << endl;
    }
}

vector<string> split(string input, char delimiter) {
    vector<string> result;
    stringstream ss(input);
    string temp;

    while (getline(ss, temp, delimiter)) {
        result.push_back(temp);
    }

    return result;
}
반응형