c++ 문장 띄어쓰기로 구분하기

이주희·2022년 1월 19일
0

Algorithm

목록 보기
4/24

문장을 띄어쓰기 기준으로 나누는 방법

stringstream이란?

주어진 문자열에서 필요한 자료형에 맞는 정보를 꺼내기 유용..
공백과 \n 제외하고 단어 기준 구분하기 좋다.


#include <sstream>

위의 헤더파일 추가


stringstream ss;

//1
ss.str("  ");

//2
ss<<" ";

위의 두가지 방법을 이용하여 stringstream에 문장을 넣어준다.

string n;
while(ss>>n)cout<<n<<endl;

전체 단어 출력하기 (n이 string이기 때문에 string만 뽑아내게 된다.)

istringstream이란?

문자열을 작은 단위로 나눌때 유용
작은 단위로 나누면서 자료형도 각각 원하는 것으로 바꿀 수 있다.

	istringstream iss(" my name is 111");
	string s1,s2,s3;
	int n;
	iss>>s1>>s2>>s3>>n;
	cout<<s1<<endl;
	cout<<s2<<endl;
	cout<<s3<<endl;
	cout<<n<<endl;

0개의 댓글