본문 바로가기
프로그램/C++ 1000제

C++ 55제] vector 사용, 입력된 문자열을 단어별로 출력하시오.

by 건티 2022. 6. 23.
728x90

출처 : 반크_세계유산 석굴암

 

문제]

임의의 영문 문자열을 입력하여 입력된 문자열을 단어별로 출력하고 단어의 개수가 몇 개가 되는가를 구하는 프로그램을 작성하시오.
 
출력 예)
영문 문자열을 입력하시오 : I Like KunTi. You Know!
입력된 단어는 아래와 같습니다.
I
Like
KunTi.
You
Know!

 

참고풀이1]

#include <iostream>
#include <vector>
#include <string> //string, getline()
#include <sstream> //istringstream()
using namespace std;

int main()
{
   string Str;//문자열 입력변수
   string Word;//단어 변수 
   vector<string> v;//문자열에서 분리한 단어 넣을 vector변수
   int i;//반복 또는 인덱스 변수

   cout << "임의의 문자열을 입력하시오 : ";
   getline(cin, Str);
   istringstream str(Str);

   //vector에 단어 단위로 저장한다.
   while(str>>Word)
      v.push_back(Word);

   //결과출력
   for(i=0;i<v.size();i++)
      cout << v[i] << endl;

   return 0;
}

 

참고풀이1 결과]

 

참고풀이2]

#include <iostream>
#include <string> //string
#include <sstream> //istringstream()
#include <algorithm> //copy()
#include <iterator> //istream_iterator(), ostream_iterator()
using namespace std;

int main()
{  
   string Str;

   //입력부분 
   cout << "임의의 문자열을 입력하시오 : ";
   getline(cin, Str);

   istringstream iss(Str); 

   //출력부분 
   copy(istream_iterator<string>(iss), istream_iterator<string>(), ostream_iterator<string>(cout, "\n"));

   return 0;
}

 

참고풀이2 결과]

 

 

 

 

 

대한민국의 아름다운 영토, 독도의 겨울

 

반응형

댓글