백준 algorithm

백준 9093 - 단어 뒤집기

cosmohoo 2020. 2. 20. 23:39
반응형

문제 설명

=>string을 cin으로 받을 경우 buffer에 값이 남으므로 getline함수를 사용해 입력받았다. 

 

=> 

  cin.clear();
  cin.ignore(256, '\n');

위의 두가지 함수를 사용하여 buffer를 지우고 getline을 실행하였다. 

 

 

=> 우선적으로 string을 입력받은 후에 해당 string을 ' '(빈칸)이 나올 때 까지 나눠 char형 스택에 쌓았다. 

=> 스택에 쌓인 char를 하나씩 프린트하면, 해당 단어의 거꾸로 출력이 완성된다. 

=>해당 줄이 끝날 때까지 과정을 계속한다.

 

#include <iostream>
#include <string>
#include <stack>

using namespace std;

void printS(string s)
{
    int x = 0;
    stack<char> st;
    int size = s.size()-1;
    while (x <= size)
    {
        if (s[x] != ' ')
            st.push(s[x]);
        else
        {
            while (!st.empty())
            {
                cout << st.top();
                st.pop();
            }
            cout << ' ';
        }
        ++x;
    }
    while (!st.empty())
    {
        cout << st.top();
        st.pop();
    }
    cout << '\n';
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int N;
    cin >> N;
    cin.clear();
    cin.ignore(256, '\n');
    string s;

    for (int i = 0; i < N; ++i)
    {
        getline(cin, s);
        printS(s);
        s.clear();
    }
    cout << '\n';
    return 0;
}
반응형