杭電2072,因?yàn)殄e(cuò)誤的理解了題目,沒有注意到“不同”,所以我寫的程序只能夠檢測出單詞的數(shù)量,代碼如下:
#include<stdio.h> #include < string .h> /* * scanf("%s") 遇到空格,tab,和回車時(shí)結(jié)束,如s s s s表示為4個(gè)字符串 * 因此要讀入帶有空格的字符串使用 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] != ' ' ){ // 如果不是空格那么就是單詞,故數(shù)量加一 count++ ; do { // 跳過這個(gè)單詞。 if (i != len - 1 ) i++ ; else break ; } while (str[i] != ' ' ); // 跳過這個(gè)單詞。 } i ++ ; } printf( " %d\n " , count); } // while return 0 ; }
雖然是錯(cuò)誤代碼,但也有一些收獲,其中對(duì)scanf對(duì)于字符串的使用有了更深刻的認(rèn)識(shí)。若要得出不同的單詞數(shù)量,我們首先回想到將讀到的單詞裝入set中,然后就可以得到set大小,即單詞的數(shù)量。以下為使用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 ' ){ // 跳過這個(gè)單詞 str += c; c = cin. get (); } // 跳過這個(gè)單詞 if (str.length()){ words.insert(str); str = "" ; } if ( ' \n ' == c){ cout << words.size() << endl; words.clear();str = "" ; } } // while return 0 ; }
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
