题目描述
给出一段字符,请统计这段字符有几行,几个单词和几个字符。
定义单词为用空格或者换行符隔开的连续字符
字符定义为包括一般可见字符以及空格
输入描述:
第一行一个正整数T ,代表测试数据的组数
第二行开始为第一组测试数据,测试数据每行不超过1024个字符
每两组测试数据之间用连续的 5 个= 分隔,保证测试数据中不会出现连续的 5 个 =
输出描述:
每组测试数据在一行中输出由空格分隔的3个整数,分别代表行数,单词数和字符数
输入
2
This is a sample input.
Hello World!!
=====
The speech by Hunyak, translated, is:
"What am I doing here?
They say, the famous Hungarian police,
that I held down my husband and chopped off his head.
But I didn't do it, I am not guilty.
I can't believe that Uncle Sam says I did it.
They say I didit, but really I didn't."
输出
2 7 37
8 55 270
说明
对于第一个样例,有2行7个单词是显而易见的
有28个字母,3个标点符号以及6个空格,所以共有37个字符
请注意换行符不算在字符个数里
在写这个题目之前,我先来简单介绍一下stringstream的用法吧,stringstream能从从从输入的getline字符串中截取一段一段的单词或者整数。
比如
#include<bits/stdc++.h>
using namespace std;
int main(){
string s = "Hello world";
stringstream ss(s);//将字符串s复制到ss中去
string a;
while(ss >> a){
cout << a << endl;
}
cout << endl;
string str = "aaa bbb 167 ccc";
stringstream cs(str);
string x,y,z;
int b;
cs >> x >> y >> b >> z;
cout << x << endl << y << endl << b <<endl << z;
return 0;
}
运行结果
简单知道了stringstream的用法之后我们这道题就好解了,通过的代码如下
#include<bits/stdc++.h>
using namespace std;
int flag = 1;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
cin >> t;
//getchar();
while(t--){
string s;
int sum = 0,words = 0,Char = 0;
while(getline(cin,s)){
if(s == "=====")break;
sum ++;
int len = s.length();
Char += len;
stringstream ss(s);
while(ss >> s){
words++;
}
}
if(flag==1){
cout<<sum-1<<" "<<words<<" "<<Char<<"\n";
flag++;
}
else if(flag > 1)cout<<sum<<" "<<words<<" "<<Char<<"\n";
}
return 0;
}