Posted on 2007-07-06 23:49
停留的風 閱讀(441)
評論(0) 編輯 收藏 所屬分類:
C語言學習歷程
為了使得程序更加靈活,我們將不限制用戶輸入的行數。因此,我們需要找到一種方式,用于通知程序用戶已經完成輸入。有一個簡單的方法可以完成這個任務,那就是當用戶輸入最后一行文字以后,再額外加一個空行。當我們使用readLine()函數讀取這個額外的空行時,程序將在用作緩沖區的數組的第一個位置上存儲一個空字符。我們程序可以專門檢查這種特殊的情況,并由此得知用戶已經完成了輸入。
#include <stdio.h>
//判斷是否是字母
bool alphabetic(const char c)
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
{
return true;
}
else
return false;
}
//計算單詞的個數
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;
}
//得到一個字符串
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;
}
測試運行圖: