문제 풀 때 입력값을 화나게 주는 경우가 많다.
Input :
"Hello World!"
띄어쓰기로 알아서 단어를 구분하세요~
라고 하면 눈물 한방울 흘리고 반복문 돌린다.
// find로 ' '를 찾는 방법도 있다.
for(char Letter : Input)
{
if(Letter == ' ')
{
/*
이전까지의 단어 저장
단어를 일일히 하나씩 저장하던 substr을 하던
*/
}
}
이런 상황을 스트림을 사용해서 코드를 간단하게 짤 수 있다.
#include <sstream>
string Input = "Jenny Student";
string Name, Type;
stringstream Temp(Input);
Temp >> Name >> Type;
cout << Name << '\t' << Type;
// Jenny Student 출력
cin cout 처럼 비트 연산자가 오버로딩 되어있다.string Temp = "Hello World!";
stringstream Temp(Hello World!);
string Word1, Word2;
Temp >> Word1 >> Word2;
cout << Word1 << ", "<< Word2;
//Hello, World 출력됨
string Original = "1 2 3 4";
stringstream sstream(Original);
int first, second, third, fourth;
sstream >> first >> second >> third >> fourth;
// 각 변수의 값이 1 2 3 4로 초기화된다.
string + string 이건 제일 느림string += string 이정도인데 이건 insert랑 같은 코드고, stringstream이랑 성능이 비슷하다고 한다.for(char Letter : Input)
{
if(Letter == ' ')
{
/*
이전까지의 단어 저장
단어를 일일히 하나씩 저장하던 substr을 하던
*/
}
}
int라면 stoi 연산을 거치기 때문에 Letter - '0' 연산을 하는 것보다는 느리다.쉬프트 연산(>>, <<)의 결과는 istream이나 ostream객체인데
해당 객체의 bool 변환 연산(캐스팅 아님!)은 basic_ios에서 오버로딩 되어 있다.
해당 변수의 goodbit, eofbit/failbit, badbit를 모두 검사하여 bool을 반환해준다.
while(ss >> c) // bool로 캐스팅 될 때 연산이 특수화 되어 있다.
{
cout << c;
}
대충 이렇게 하면 문자 끝날 때까지만 루프를 돈다는 거지