杭電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
;
}
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

