杭电2072,因为错误的理解了题目,没有注意到“不同”,所以我写的程序只能够检测出单词的数量,代码如下:
#include<stdio.h>
#include
<
string
.h>
/*
* scanf("%s") 遇到空格,tab,和回车时结束,如s s s s表示为4个字符串
* 因此要读入带有空格的字符串使用 gets()方法。
*/
char
str[
10000
];
int
main(){
char
end ;
int
i, len, count;
while
(
1
){
count
=
0
;i =
0
;
gets(str);
if
(str[
0
] ==
'
#
'
)
break
;
len
=
strlen(str);
while
( i <
len ){
if
(str[i] !=
'
'
){
//
如果不是空格那么就是单词,故数量加一
count++
;
do
{
//
跳过这个单词。
if
(i != len -
1
) i++
;
else
break
;
}
while
(str[i] !=
'
'
);
//
跳过这个单词。
}
i
++
;
}
printf(
"
%d\n
"
, count);
}
//
while
return
0
;
}
虽然是错误代码,但也有一些收获,其中对scanf对于字符串的使用有了更深刻的认识。若要得出不同的单词数量,我们首先回想到将读到的单词装入set中,然后就可以得到set大小,即单词的数量。以下为使用set的代码。
#include<iostream>
#include
<
set
>
#include
<
string
>
using
namespace
std;
set
<
string
>
words;
int
main(){
string
str =
""
;
char
c;
while
((c = cin.
get
()) !=
'
#
'
){
while
(c !=
'
'
&& c !=
'
\n
'
){
//
跳过这个单词
str
+=
c;
c
= cin.
get
();
}
//
跳过这个单词
if
(str.length()){
words.insert(str);
str
=
""
;
}
if
(
'
\n
'
==
c){
cout
<< words.size() <<
endl;
words.clear();str
=
""
;
}
}
//
while
return
0
;
}

