coding_test/BAEKJOON
백준 12065번 C++ 풀이
CodeJin
2022. 1. 2. 16:12
https://www.acmicpc.net/problem/12605
12605번: 단어순서 뒤집기
스페이스로 띄어쓰기 된 단어들의 리스트가 주어질때, 단어들을 반대 순서로 뒤집어라. 각 라인은 w개의 영단어로 이루어져 있으며, 총 L개의 알파벳을 가진다. 각 행은 알파벳과 스페이스로만
www.acmicpc.net

문장을 입력받고, 단어 단위로 뒤집어서 출력하는 문제. 문장 전체를 입력받고, 공백을 기준으로 파싱하여 스택에 push하고 push가 끝난 후에, pop하면서 출력한다.
C++에서 문자열을 파싱하는 방법을 몰랐는데, stringstream기능을 이용하여 할 수 있다는 것을 배웠다.
(https://rank-brothers.com/831/cpp-string-tokenizing/)
#include <iostream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;
int main () {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int test;
stack<string> st;
string str;
string token;
cin >> test;
cin.ignore();
for (int i = 1; i <= test; ++i) {
getline(cin, str);
stringstream sstream(str);
while(getline(sstream, token, ' ')) st.push(token);
cout << "Case #" << i << ": ";
while (!st.empty()) {
token = st.top();
st.pop();
cout << token << ' ';
}
cout << '\n';
}
}
