백준 - 1152번 단어의 개수(문자열, isspace)

Kiwoong Park·2023년 5월 11일
0

C++에선 whitespace가 "True"임을 명심하자

there is a difference between single quotes (' ') and double quotes (" ") in C++.

In C++, single quotes are used to denote a single character literal. For example, 'a' represents the character 'a', and ' ' represents the space character.

On the other hand, double quotes are used to create string literals. For example, "hello" represents the string "hello". A string literal is actually an array of characters with an implicit null character ('\0') at the end.

#include<iostream>
using namespace std;
int main(){
    int tot=0;
    string str;
    getline(cin,str);
    for(int i=0;i<str.length();i++)
        if (!isspace(str[i]) && (isspace(str[i+1]) || str[i+1] == '\0')) tot++;
    cout << tot;
    
    
}

So, in the context of your code, when checking for a space character, you should use single quotes like ' ' to represent the space character, not double quotes like " ".

The isspace function simplifies the condition and makes the code more readable. By using isspace(str[i]), we directly check if str[i] is a whitespace character. Additionally, the second part of the condition !isspace(str[i + 1]) ensures that the character following str[i] is not a whitespace character. If both conditions are true, we increment tot to count the occurrence.

#include<iostream>
using namespace std;
int main(){
    int tot=0;
    string str;
    while(cin>>str) tot++;
    cout << tot;
}
#import<ios>
int c;main(){while(!scanf("%*s"))c++;printf("%d",c);}
profile
You matter, never give up

0개의 댓글