经典代码一

来源:互联网 发布:discuz数据库备份目录 编辑:程序博客网 时间:2024/04/29 23:55

        现在看每本C 语言基础的入门书里面都有些这样的代码:不断地在每本教材中出现,开始的时候感觉简单,后来就觉得这些经典的东西很主要。

1、将输入复制到输出。

#include    <stdio.h>int main(void){    int c;    while( (c = getchar()) != EOF )     {putchar(c);    }    return 0;}

2、统计输入的字符数

#include    <stdio.h>int main(void){    int nc;    for( nc = 0; getchar() != EOF ; ++nc )    {;    }    printf("%d\n", nc);    return 0;}

3、统计输入中的行数

#include    <stdio.h>int main(void){    int c;    int n1 = 0;    while( (c = getchar()) != EOF )    {if( '\n' == c ){    ++ n1;}    }    printf("%d\n", n1);    return 0;}

4、单词计数

#include    <stdio.h>#define     IN 1  /*  在单词内  */#define     OUT 0 /*  在单词外  *//* 统计输入的行数、单词数与字符数 */int main(void){    int c;    int n1, nc, nw;    int state;    state = OUT;    n1 = nw = nc = 0;    while( (c = getchar()) != EOF )    {if( '\n' == c ){    ++ n1;}if( ' ' == c || '\n' == c || '\t' == c ){    state = OUT;}else if( OUT == state ){    state = IN;    ++ nw;}    }    printf("%d %d %d \n", n1 , nw, nc);    return 0; }

5、统计各个数字、空白符及其他字符出现的次数

#include    <stdio.h>int main(void){    int c;    int nwhite;    int nother;    int ndigit[10];    nwhite = nother = 0;    for( int i = 0; i < 10 ; ++ i )    {ndigit[i] = 0;    }        while( (c = getchar()) != EOF )    {if( c >= '0' && c <= '9'){    ++ ndigit[c - '0']}else if( ' ' == c || '\n' == c || '\t' == c ){   ++ nwhite; }else if( OUT == state ){   ++ nother;}    }    printf("digits =");    for( i = 0; i < 10 ; ++ i )    {printf("%d", ndigit[i]);    }    printf(",white space = %d, other = %d", nwhite, nother);    return 0; }

6、打印输入中最长的行

#include    <stdio.h>#define     MAXLINE 1000 //允许的输入行的最大长度int getline(char line[], int maxine);void copy(char to[], char from[])//打印最长的输入行int main(void){    int len;                      //当前行长度    int max;                      //目前为止发现的最长行的程度     char line[MAXLINE];           //当前的输入行    char longest[MAXLINE];        //用于保存最长的行    max = 0;    while( (len = getline(line, MAXLINE)) > 0)    {if( len > max ){    max = len;    copy(longest, line);}    }    if( max > 0 )                 //存在这样的行    {printf("%s", longest);    }    return 0; }//getline函数:将一行读入到s中并返回长度int getline(char s[], int lim){    int c , num;    for( num = 0; num < lim - 1 && EOF != (c = getchar()) && '\n' != c; ++ num )    {s[num] = c;    }    if( '\n' == c )    {s[num] = c;++ num;    }    s[num] = '\0';    return num;}//copy函数:将from复制到to;这里假定to足够大void copy(char to[], char from[]){    int i;    i = 0;    while( (to[i] == from[i]) != '\0' )    {++ i;    }}


原创粉丝点击