https://www.acmicpc.net/problem/9093
#include <iostream>
#include <stack>
using namespace std;
stack<char> s;
int main()
{
int T;
char input;
cin >> T;
for(int i=0 ; i<T ; i++){
while(1){
cin >> input;
if (input == ' ' || input == '\n'){
while(!s.empty()){
cout << s.top();
s.pop();
}
if (input == '\n')
break;
}
else
s.push(input);
}
}
}
다음 코드의 문제점
1. cin이 개행 문자를 못 읽음
-> cin.get() 을 쓴다!
2. 엔터를 무조건 출력하는 문제
-> cin.ignore() 로 엔터를 무시해준다 / or getline 함수를 써준다 (getline으로 읽고 마지막에 공백 추가해줘야함)
3. 현근이가 if 조건문안에 두개 다 넣어버림 ㅎ
난 저거 싫단말이다
#include <iostream>
#include <stack>
using namespace std;
stack<char> s;
int main()
{
int T;
char input;
cin >> T;
cin.ignore();
for (int i = 0; i < T; i++){
while (1){
cin.get(input);
if (input == ' ' || input == '\n'){
while (!s.empty()){
cout << s.top();
s.pop();
}
cout << ' ';
if (input == '\n')
break;
}
else
s.push(input);
}
}
}
cin을 cin.get()으로 바꿨지만...
이건 시간초과가 뜸!
-> while을 못빠져나오는듯
while을 쉽게 빠져나올 수 없을까???
while(T--)를 하면 됨!!!!!!! ㅁㅊㄷ
+ 그냥 getline 함수 쓰기로 함 - getline 전에 cin이 있다면 cin.ignore()로 버퍼 초기화 해주는 거 잊지말기!!!
C++ 입력 함수 참고 글 https://kyu9341.github.io/C-C/2020/01/17/C++getline()/
#include <iostream>
#include <stack>
using namespace std;
stack<char> s;
int main()
{
int T;
string str;
cin >> T;
cin.ignore(); // cin 다음에 getline 쓸 거니까 버퍼 초기화 해줘야 함!
while(T--){
getline(cin,str);
str += ' '; // 개행 문자를 인식하는 대신에 아예 개행까지만 받기 + str 마지막에 공백을 넣어서 pop했을 때 나오는 방법
for(int i=0 ; i<str.length() ; i++){
if(str[i] == ' '){
while (!s.empty()){
cout << s.top();
s.pop();
}
cout << ' ';
}
else
s.push(str[i]);
}
}
}
아무튼 최종!!!
728x90
'백준' 카테고리의 다른 글
백준 7568 C++ (2) | 2023.11.22 |
---|---|
백준 1018 C++ (0) | 2023.11.18 |
백준 1874번 C++ (1) | 2023.11.15 |
백준 2805번 C++ (0) | 2023.11.15 |
백준 2667 c++ 런타임 에러 (OutOfBounds) (0) | 2023.08.25 |