[boj] (b2) 1152 단어의 개수

강신현·2022년 3월 31일
0

✅ 완전탐색 ✅ getline(cin, str)

문제

풀이

문제자체는 완전탐색으로 공백을 세면 단어의 개수를 세면되므로 어렵지 않다.
하지만 공백을 포함하여 문자열을 받아야 하므로 그냥 cin으로 입력받으면 안되고 getline(cin, str) 으로 입력 받아야 한다.

주의

문자열 맨앞과 맨뒤에 공백이 들어가 있는 경우를 생각해야 함

코드

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    string str;
    getline(cin, str);

    int cnt = 1;
    if(str[0] == ' '){
        for (int i = 1; i < str.length(); i++)
        {
            if (str[i] == ' ')
                cnt++;
        }
    }
    else{
        for (int i = 0; i < str.length(); i++)
        {
            if (str[i] == ' ')
                cnt++;
        }
    }

    if(str[str.length()-1] == ' ') cnt--;

    cout << cnt << "\n";

    return 0;
}
profile
땅콩의 모험 (server)

0개의 댓글