1.數組
編寫一個程序,以統計各個數字、空白符(包括空格符、製表符及換行符)以及所有其它字符出現的次數。這個程序的實用意義不大,但可以通過該程序討論C語言多方面的問題。
所有的輸入字符可以分爲12類(數字10類,空白符1類,其他字符1類),因此可以用一個數組存放各個數字出現的次數,這樣比實用10個 獨立的變量更方便,下面是該程序的一種版本:
#include <stdio.h>
/* 統計各個數字、空白符、及其他字符出現的次數 */
void main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for(i = 0; i < 10; ++i)
{
ndigit[i] = 0;
}
while((c = getchar()) != EOF)
if(c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for(i = 0; i <10; ++i)
printf("%d",ndigit[i]);
printf(", white space = %d , other = %d \n",nwhite,nother);
}
編譯在Ubuntun下編譯,運行,測試結果如下:
2.字符數組
字符數組是C語言中最常用的數組類型。下面我們通過編寫一個程序來說明字符數組以及操作字符數組的函數的用法。該程序讀入一組文本行,並把最長的文本行打印出來,該算法的基本框架非常簡單:
while(還有爲處理的行)
if(該行比已處理的最長行還要長)
保存該行
保存該行的長度
打印最長的行
代碼如下所示:
#include <stdio.h>
//允許輸入行的最大長度
#define MAXLINE 1000
int mygetline(char line[],int maxline);
void copy(char to[],char from[]);
/* 打印最長的輸入行 */
int main()
{
int len; //當前行長度
int max; //目前爲止發現最長行的長度
char line[MAXLINE]; //當前的輸入行
char longest[MAXLINE]; //用於保存最長的行
max = 0;
while((len = mygetline(line,MAXLINE)) > 0 )
if(len > max)
{
max = len;
copy(longest, line);
}
if(max >0) //存在這樣的行
printf("\nresult is: %s",longest);
return 0;
}
/* mygetline函數:將一行讀入S中並返回其長度 */
int mygetline(char s[], int lim)
{
int c, i;
for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n' ; ++i)
s[i] = c;
if(c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy函數:將from複製到to;這裏假定to足夠大 */
void copy(char to[], char from[])
{
int i;
i = 0;
while((to[i] = from[i]) != '\0')
++i;
}
編譯在Ubuntun下編譯,運行,測試結果如下:
說明:getline是C++標準庫函數;但不是C標準庫函數。
爲了避免函數衝突,代碼中定義了 "mygetline" 函數。