Notice
Recent Posts
Recent Comments
Link
Little Jay
[C++] 백준 12605번 단어순서 뒤집기 본문
cin의 버퍼 문제때문에 조금 푸는데 애가 먹었다
https://m.blog.naver.com/cksdn788/221239805238
[Grind Away] C++ getline 사용시 buffer clear 문제 깔끔하게 해결하기
C++에서 getline 함수를 사용할 시 입력 버퍼상의 '\n'문자까지 읽어들인다. 하지만 일반적인 cin >>...
blog.naver.com
이 분의 블로그를 참조해서 buffer을 clear하는 방법을 배웠다.
cin을 하면 개행문자까지 읽기 때문에
getline을 할때 첫 번째 for문에서 '\n'을 받아버리는 경우가 발생해버렸다.
이를 cin.ignore()을 사용하면 간단하게 해결이 가능하다는 사실을 배웠다.
생각보다 까다로운 Bronze 1 문제였던 것 같다.
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <sstream>
using namespace std;
stack<string> tokenize_getline(const string& data, const char delimiter = ' ') {
stack<string> result;
string token;
stringstream ss(data);
while (getline(ss, token, delimiter)) {
result.push(token);
}
return result;
}
int main() {
int n;
cin >> n;
cin.ignore();
for (int i = 0; i < n; i++) {
string data;
getline(cin, data);
stack<string> st = tokenize_getline(data, ' ');
cout << "Case #" << i + 1 << ":" << " ";
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
cout << '\n';
}
return 0;
}'알고리즘 > BOJ' 카테고리의 다른 글
| [C++] 백준 11051번 이항 계수 2 (0) | 2021.08.05 |
|---|---|
| [C++] 백준 2839번 - 설탕 배달 (0) | 2021.08.04 |
| [C++] 백준 2805번 나무 자르기 (0) | 2021.08.04 |
| [C++] 백준 1021번 회전하는 큐 (0) | 2021.08.04 |
| [C++] 백준 4949번 균형잡힌 세상 (0) | 2021.08.03 |
Comments