全红求助!!

B2120 单词的长度

CoderMC @ 2025-01-10 16:27:54

#include<bits/stdc++.h>
using namespace std;
int len;
string s;
int main(){
    cin>>s;
    int cnt=0;
    int len=s.size();
   // getline(cin,s);
    for(int i=0;i<len;i++){
        if(s[i]==' '){
            cout<<cnt<<',';
            cnt=0;
        }
        else {
            cnt++;
        }
    }
    cout<<cnt<<endl;
    return 0;
}

by chengjindong @ 2025-01-10 16:39:49

cin>>s; 改成 getline(cin,s);,这题要输入整行


by chengjindong @ 2025-01-10 16:41:10

如果只有一个空格,还会输出一次“0,”,特判一下


by chengjindong @ 2025-01-10 16:42:08

#include<bits/stdc++.h>
using namespace std;
int len;
string s;
int main(){
//    cin>>s;
    int cnt=0;
    getline(cin,s);
    int len=s.size();
    for(int i=0;i<len;i++){
        if(s[i]==' '){
            if(cnt!=0){
                cout<<cnt<<',';
                cnt=0;
            }
        }
        else {
            cnt++;
        }
    }
    cout<<cnt<<endl;
    return 0;
}

by chengjindong @ 2025-01-10 16:43:04

@CoderMC


by CoderMC @ 2025-01-10 17:16:46

@chengjindong太酷啦!感谢!!


|