Training/HackerRank

[C++][Strings] StringStream

FATKITTY 2021. 8. 4. 00:54
반응형

https://www.hackerrank.com/challenges/c-tutorial-stringstream/problem

 

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

vector<int> parseInts(string str) {
    vector<int> result;
    stringstream ss;
    char ch;
    int n;
    
    // stringstream object called ss encapsulates a string
    // and allows access to string as we could access any other stream
    ss.str(str);
    
    while (ss >> n) {
        result.push_back(n);
        
        // gets rid of all the commas and make the loop work
        ss >> ch;
    }
    
    return result;
}

int main() {
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }
    
    return 0;
}

 

반응형

'Training > HackerRank' 카테고리의 다른 글

[C++][STL] Vector-Erase  (0) 2021.08.07
[C++][Classes] Class  (0) 2021.08.07
[C++][Introduction] Pointer  (0) 2021.08.03
[C++][Implementation] Breaking the Records  (0) 2021.08.01
[C++][Implementation] Number Line Jumps  (0) 2021.07.30