Posted on 2007-07-06 23:49
停留的風(fēng) 閱讀(441)
評(píng)論(0) 編輯 收藏 所屬分類:
C語(yǔ)言學(xué)習(xí)歷程
為了使得程序更加靈活,我們將不限制用戶輸入的行數(shù)。因此,我們需要找到一種方式,用于通知程序用戶已經(jīng)完成輸入。有一個(gè)簡(jiǎn)單的方法可以完成這個(gè)任務(wù),那就是當(dāng)用戶輸入最后一行文字以后,再額外加一個(gè)空行。當(dāng)我們使用readLine()函數(shù)讀取這個(gè)額外的空行時(shí),程序?qū)⒃谟米骶彌_區(qū)的數(shù)組的第一個(gè)位置上存儲(chǔ)一個(gè)空字符。我們程序可以專門檢查這種特殊的情況,并由此得知用戶已經(jīng)完成了輸入。
#include <stdio.h>
//判斷是否是字母
bool alphabetic(const char c)
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
{
return true;
}
else
return false;
}
//計(jì)算單詞的個(gè)數(shù)
int countWords(const char string[])
{
int i,wordCount=0;
bool lookingForWord=true,alphabetic(const char c);
for(i=0;string[i]!='\0';++i)
{
if(alphabetic(string[i]))
{
if(lookingForWord)
{
wordCount++;
lookingForWord=false;
}
}
else
lookingForWord=true;
}
return wordCount;
}
//得到一個(gè)字符串
void readLine(char buffer[])
{
char character;
int i=0;
do
{
character=getchar();
buffer[i]=character;
++i;
}while(character!='\n');
buffer[i-1]='\0';
}
int main(void)
{
char text[81];
int totalWords=0;
void readLine(char buffer[]);
bool endOfText=false;
printf("Type in your text.\n");
printf("When you are done,press'RETURN'.\n\n");
while(!endOfText)
{
readLine(text);
if(text[0]=='\0')
{
endOfText=true ;
}
else
totalWords+=countWords(text);
}
printf("\nThere are %i words in the above text.\n",totalWords);
return 0;
}
測(cè)試運(yùn)行圖: