📕공백을 포함한 문자열 입력받기
📗getline 이용
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string s;
getline(cin, s);
cout << s;
}
getline을 쓰면 알아서 공백을 포함하여 문자열을 입력받는다.
📗cin.getline()을 이용
#include <iostream>
#include <string>
using namespace std;
int main(){
char s[100];
cin.getline(s,100,'\n');
cout<<s;
}
cin.getline(char배열 이름, 배열 size, 구분 문자)
getline과 다른 점은 엔터 말고 특정 구분 문자로 입력을 종료시킬 수 있다.
📗 get_s()를 이용
#include <iostream>
#include <string>
using namespace std;
int main(){
char s[100];
gets_s(s,sizeof(s));
cout<<s;
}
get_s(char배열 이름, 배열 크기)
📕공백으로 문자열 자르기
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string s = "abc def ghi";
stringstream ss(s);
ss.str(s);
string word;
while(ss>>word){
cout<<word;
}
}
/*출력 내용
abc
def
ghi
*/
- stringstream은 주어진 문자열에서 필요한 정보를 빼낼 때 유용하게 사용된다.
- 헤더 <sstream>이 필요하다.
- while(ss> word) : 더 이상 word에 해당하는 자료형(string)에 맞는 정보가 없을 때까지 스트림에서 word로 자료를 복사한다.
- 끝에 도달하면 끝난다.
- 중간에 word와 같지 않은 자료형이 나오면 복사하지 않고 종료
- stringstream의 값은 변하지 않음.
- stringstream을 재사용하기 위해서는 clear() 함수를 사용해야 한다.
'Skils > C++' 카테고리의 다른 글
| ios_base::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)을 붙여야 하는 이유 (0) | 2022.08.16 |
|---|---|
| [C++] range based for(범위기반 for 반복문) (0) | 2022.06.23 |
| [C++]-vector 사용법 (0) | 2022.05.03 |
| [c++]- map (0) | 2022.05.01 |