갓비니

2020/04/19 코딩 문제 연습(7단계 / 백준 1152번) C++ / 띄어쓰기도 string에 저장하고 싶을 때 getline(), .at() 본문

Programming/코딩 문제 풀이

2020/04/19 코딩 문제 연습(7단계 / 백준 1152번) C++ / 띄어쓰기도 string에 저장하고 싶을 때 getline(), .at()

갓비니 2020. 4. 21. 16:06

흠..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<string>
using namespace std;
 
int main() {
 
    string word;
    int count = 1;
    getline(cin, word);
 
    for (int i = 0;i<word.length(); i++) {
        if (word[i] == ' ')count++;
 
    }
    if (word[0== ' ')count--;
    if (word[word.length()-1== ' ')count--;
 
    cout << count;
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

<getline 함수>

getline은 띄어쓰기도 함께 입력받고싶을 때 저장한다.

본래 cin은 띄어쓰기를 기준으로 한 문자라고 입력받기 때문에....

 

1. cin.getline (= std::cin.getline(배열명, 저장할 문자 최대값,(어느문자를 기준으로 나눌건지, 디폴트는 \n)) )  *iostream에 지정

 

2. getline(cin,string이름) *string에 지정

 

두가지가 있다.

 

<string 관련 함수들>

1. stringname.at(index) -> 접근하고 싶은 인덱스에 해당하는 문자를 반환한다. 범위를 넘어가면 예외를 반환한다.

2. stringname[index] -> 접근하고 싶은 인덱스에 해당하는 문자를 반환한다. 예외를 반환하지 않는다.

3. stringname.front() / stringname.back() -> 맨 앞, 뒤를 반환

4. stringname.size() / stringname.length() 등...