C_Primer_Plus(第五版)全书源代码

// chapter 01

/*

#include <stdio.h>

int main(void)

{

    int dogs;

 

    printf("How many dogs do you have?/n");

    scanf("%d", &dogs);

    printf("So you have %d dog(s)!/n", dogs);

 

    return 0;

}

*/

//

//

//chapter 02

// fathm_ft.c -- converts 2 fathoms to feet

/*

#include <stdio.h>

int main(void)

{

    int feet, fathoms;

 

    fathoms = 2;

    feet = 6 * fathoms;

    printf("There are %d feet in %d fathoms!/n", feet, fathoms);

    printf("Yes, I said %d feet!/n", 6 * fathoms);

 

    return 0;

}

*/

//

/*

#include <stdio.h>

int main(void)                // a simple program           

{

    int num;                  // define a variable called num

    num = 1;                  // assign a value to num       

 

    printf("I am a simple "); // use the printf() function   

    printf("computer./n");

    printf("My favorite number is %d because it is first./n",num);

  

    return 0;

}*/

//

// two_func.c -- a program using two functions in one file

/*

#include <stdio.h>

void butler(void);      // ISO/ANSI C function prototyping

int main(void)

{

    printf("I will summon the butler function./n");

    butler();

    printf("Yes. Bring me some tea and writeable CD-ROMS./n");

  

    return 0;

}

 

void butler(void)          // start of function definition

{

    printf("You rang, sir?/n");

}

*/

//

//

//chapter 03  数据和C

/*

// altnames.c -- portable names for integer types

#include <stdio.h>

#include <inttypes.h> // supports portable types       the system doesn't contain the header file

int main(void)

{

    int16_t me16;     // me16 a 16-bit signed variable

  

    me16 = 4593;

    printf("First, assume int16_t is short: ");

    printf("me16 = %hd/n", me16);

    printf("Next, let's not make any assumptions./n");

    printf("Instead, use a /"macro/" from inttypes.h: ");

    printf("me16 = %" PRId16 "/n", me16); 

   

    return 0;

}

*/

//

/*

// bases.c--prints 100 in decimal, octal, and hex

#include <stdio.h>

int main(void)

{

    int x = 100;

   

    printf("dec = %d; octal = %o; hex = %x/n", x, x, x);

    printf("dec = %d; octal = %#o; hex = %#x/n", x, x, x);

    //%# 十六进制前显示 Ox   // 八进制数前显示o

    return 0;

}

 

*/

//

/*

// charcode.c-displays code number for a character

#include <stdio.h>

int main(void)

{

    char ch;

   

    printf("Please enter a character./n");

    scanf("%c", &ch);  

    printf("The code for %c is %d./n", ch, ch);

   

    return 0;

}

*/

//

/*

//print1.c-displays some properties of printf()

#include <stdio.h>

int main(void)

{

    int ten = 10;

    int two = 2;

   

    printf("Doing it right: ");

    printf("%d minus %d is %d/n", ten, 2, ten - two );

    printf("Doing it wrong: ");

    printf("%d minus %d is %d/n", ten );  // forgot 2 arguments

 

    return 0;

}

*/

//

/* print2.c-more printf() properties */

/*

#include <stdio.h>

int main(void)

{

    unsigned int un = 3000000000; // system with 32-bit int

    short end = 200;              // and 16-bit short     

    long big = 65537;

     long verybig = 12345678908642;

   

         //C 也可以使用前缀h 来表示short 类型。

         // 因此%hd 显示一个十进制的short 整型。%ho 为八进制形式。

    printf("un = %u and not %d/n", un, un);

    printf("end = %hd and %d/n", end, end);

    printf("big = %ld and not %hd/n", big, big);

    printf("verybig= %lld and not %ld/n", verybig, verybig);

   

    return 0;

}

*/

//

 

/* showf_pt.c -- displays float value in two ways */

/*

#include <stdio.h>

int main(void)

{

    float aboat = 32000.0;

    double abet = 2.14e9;

    long double dip = 5.32e-5;

  

    printf("%f can be written %e/n", aboat, aboat);

    printf("%f can be written %e/n", abet, abet);

    printf("%f can be written %e/n", dip, dip);

  

    return 0;

}

*/

//

/* toobig.c-exceeds maximum int size on our system */

/*

#include <stdio.h>

int main(void)

{

    int i = 2147483647;

    unsigned int j = 4294967295;

 

    printf("%d %d %d/n", i, i+1, i+2);

    printf("%u %u %u/n", j, j+1, j+2);

  

    return 0;

}

*/

//

/* typesize.c -- prints out type sizes */

/*

#include <stdio.h>

int main(void)

{

// c99 provides a %zd specifier for sizes

    printf("Type int has a size of %u bytes./n", sizeof(int)); //4 bytes

    printf("Type char has a size of %u bytes./n", sizeof(char));// 1 bytes

    printf("Type long has a size of %u bytes./n", sizeof(long));//4 bytes

    printf("Type double has a size of %u bytes./n", sizeof(double));//8 bytes

    return 0;

}

*/

//

//

// chapter04  字符串的格式化输入/ 输出

// defines.c -- uses defined constants from limit.h and float.              // this is useful ,you can know some limits of the system

/*

#include <stdio.h>

#include <limits.h>    // integer limits

#include <float.h>     // floating-point limits

int main(void)

{

    printf("Some number limits for this system:/n");

    printf("Biggest int: %d/n", INT_MAX);

    printf("Smallest long long: %lld/n", LONG_MIN);

    printf("One byte = %d bits on this system./n", CHAR_BIT);

    printf("Largest double: %e/n", DBL_MAX);

    printf("Smallest normal float: %e/n", FLT_MIN);

    printf("float precision = %d digits/n", FLT_DIG);

    printf("float epsilon = %e/n", FLT_EPSILON);

   

    return 0;

}

 

*/

//

/* flags.c -- illustrates some formatting flags */

/*

#include <stdio.h>

int main(void)

{

    printf("%x %X %#x/n", 31, 31, 31);

    printf("**%d**% d**% d**/n", 42, 42, -42);

    printf("**%5d**%5.3d**%05d**%05.3d**/n", 6, 6, 6, 6);

 

    return 0;

}

*/

//

 

/* floatcnv.c -- mismatched floating-point conversions */

/*

#include <stdio.h>

int main(void)

{

    float n1 = 3.0;

    double n2 = 3.0;

    long n3 = 2000000000;

    long n4 = 1234567890;

 

    printf("%.1e %.1e %.1e %.1e/n", n1, n2, n3, n4);

    printf("%ld %ld/n", n3, n4);

    printf("%ld %ld %ld %ld/n", n1, n2, n3, n4);

  

    return 0;

}

 

*/

//

// floats.c -- some floating-point combinations

/*

#include <stdio.h>

 

int main(void)

{

    const double RENT = 3852.99;  // const-style constant

 

    printf("*%f*/n", RENT);

    printf("*%e*/n", RENT);

    printf("*%4.2f*/n", RENT);

    printf("*%3.1f*/n", RENT);                         //take care here

    printf("*%10.3f*/n", RENT);

    printf("*%10.3e*/n", RENT);

    printf("*%+4.2f*/n", RENT);

    printf("*%010.2f*/n", RENT);

 

    return 0;

}

 

*/

//

/* intconv.c -- some mismatched integer conversions */

/*

#include <stdio.h>

#define PAGES 336

#define WORDS 65618

int main(void)

{

    short num = PAGES;

    short mnum = -PAGES;

 

    printf("num as short and unsigned short:  %hd %hu/n", num,

            num);

    printf("-num as short and unsigned short: %hd %hu/n", mnum,

            mnum);

    printf("num as int and char: %d %c/n", num, num);

    printf("WORDS as int, short, and char: %d %hd %c/n",

            WORDS, WORDS, WORDS);

   return 0;

}

 

*/

/

/* longstrg.c -- printing long strings */

/*

#include <stdio.h>

int main(void)                                                 //take care of this program

{

    printf("Here's one way to print a ");

    printf("long string./n");

    printf("Here's another way to print a /

long string./n");

    printf("Here's the newest way to print a "

          "long string./n");      // ANSI C

    return 0;

}

*/

/

/* praise1.c -- uses an assortment of strings */

/*

#include <stdio.h>

#define PRAISE "What a super marvelous name!"

int main(void)

{

    char name[40];

 

    printf("What's your name?/n");

    scanf("%s", name);

    printf("Hello, %s. %s/n", name, PRAISE);

   printf("Hello, %s. %s/n", name, "very good");                    //take care of here

    return 0;

}

 

*/

/

/* praise2.c */

/*

#include <stdio.h>

#include <string.h>      // provides strlen() prototype

#define PRAISE "What a super marvelous name!"

int main(void)

{

    char name[40];

 

    printf("What's your name?/n");

    scanf("%s", name);

    printf("Hello, %s. %s/n", name, PRAISE);

    printf("Your name of %d letters occupies %d memory cells./n",

          strlen(name), sizeof name);

    printf("The phrase of praise has %d letters ",

         strlen(PRAISE));

    printf("and occupies %d memory cells./n", sizeof PRAISE);

 

    return 0;

}

*/

/

/* printout.c -- uses conversion specifiers */

/*

#include <stdio.h>

#define PI 3.141593

int main(void)

{

    int number = 5;

    float espresso = 13.5;

    int cost = 3100;

 

    printf("The %d CEOs drank %f cups of espresso./n", number,

         espresso);

    printf("The value of pi is %f./n", PI);

    printf("Farewell! thou art too dear for my possessing,/n");

    printf("%c%d/n", '$', 2 * cost);

 

    return 0;

}

*/

/

/* prntval.c -- finding printf()'s return value */

/*

#include <stdio.h>

int main(void)

{

    int bph2o = 212;

    int rv;

 

    rv = printf("%d F is water's boiling point./n", bph2o);

    printf("The printf() function printed %d characters./n",               // finding printf()'s return value== how many characters printed

             rv);

    return 0;

}

*/

/

/* skip2.c -- skips over first two integers of input */

/*

#include <stdio.h>

int main(void)

{

    int n;

 

    printf("Please enter three integers:/n");

    scanf("%*d %*d %d", &n);                                                  //* means skip

    printf("The last integer was %d/n", n);

  

    return 0;

}

*/

/

/* strings.c -- string formatting */

/*

#include <stdio.h>

#define BLURB "Authentic imitation!"

int main(void)

{

    printf("/%2s//n", BLURB);                                         // still don't understand clearly

    printf("/%24s//n", BLURB);

    printf("/%24.5s//n", BLURB);

    printf("/%-24.5s//n", BLURB);

  

    return 0;

}

*/

//

/* varwid.c -- uses variable-width output field */

/*

#include <stdio.h>

int main(void)

{

    unsigned width, precision;

     int number = 256;

    double weight = 242.5;

 

    printf("What field width?/n");

    scanf("%d", &width);

    printf("The number is :%*d:/n", width, number);

    printf("Now enter a width and a precision:/n");                 // still don't understand clearly

    scanf("%d %d", &width, &precision);

    printf("Weight = %*.*f/n", width, precision, weight);                //%*.*f  %24.5s what does is mean?

    printf("Done!/n");

   

    return 0;

}

*/

//

/* width.c -- field widths */

/*

#include <stdio.h>

#define PAGES 931

int main(void)

{

    printf("*%d*/n", PAGES);           // still will print 931

    printf("*%2d*/n", PAGES);            // still will print 931

    printf("*%10d*/n", PAGES);

    printf("*%-10d*/n", PAGES);

 

    return 0;

}

 

*/

//

/

//chapter 05         运算符、表达式和语句

/* add_one.c -- incrementing: prefix and postfix */

/*

#include <stdio.h>

int main(void)

{

    int ultra = 0, super = 0;

 

    while (super < 5)

    {

        super++;

        ++ultra;

        printf("super = %d, ultra = %d /n", super, ultra);

     }

   

    return 0;

}

*/

///

/* addemup.c -- four kinds of statements */

/*

#include <stdio.h>

int main(void)                // finds sum of first 20 integers

{

    int count, sum;          

    int num=0;

    count = 0;               

    sum = 0;                 

    while (count++ < 20)                  // you should take care of

    {

              num++;

              sum = sum + count;         

              printf("count= %d sum = %d/n",count, sum);

    }

       printf(" the time of loop is %d/n",num);

    return 0;

}

*/

//

 

/* bottles.c -- counting down */

/*

#include <stdio.h>

#define MAX 10

int main(void)

{

    int count = MAX + 1;

 

    while (--count > 0) {

        printf("%d bottles of spring water on the wall, "

               "%d bottles of spring water!/n", count, count);

        printf("Take one down and pass it around,/n");

        printf("%d bottles of spring water!/n/n", count - 1);

    }

 

    return 0;

}

 

*/

//

 

 

/* shoes1.c -- converts a shoe size to inches */

/*

#include <stdio.h>

#define ADJUST 7.64

#define SCALE 0.325

int main(void)

{

    double shoe, foot;

 

    shoe = 9.0;

    foot = SCALE * shoe + ADJUST;

    printf("Shoe size (men's)    foot length/n");

    printf("%10.1f %15.2f inches/n", shoe, foot);

 

    return 0;

}

*/

///

/* shoes2.c -- calculates foot lengths for several sizes */

/*

#include <stdio.h>

#define ADJUST 7.64

#define SCALE 0.325

int main(void)

{

    double shoe, foot;

 

    printf("Shoe size (men's)    foot length/n");

    shoe = 3.0;

    while (shoe < 18.5)     

    {

        foot = SCALE*shoe + ADJUST;

        printf("%10.1f %15.2f inches/n", shoe, foot);

        shoe = shoe + 1.0;

    }                    

    printf("If the shoe fits, wear it./n");

 

    return 0;

}*/

//

/* golf.c -- golf tournament scorecard */

/*

#include <stdio.h>

int main(void)

{

    int jane, tarzan, cheeta;

 

    cheeta = tarzan = jane = 68;

    printf("                  cheeta   tarzan    jane/n");

    printf("First round score %4d %8d %8d/n",cheeta,tarzan,jane);

 

    return 0;

}

*/

///

/* squares.c -- produces a table of first 20 squares */

/*                                                 // have fun ,you can learn much

#include <stdio.h>

int main(void)

{

    int num = 1;

 

    while (num < 21)

    {

 

        printf("%4d %6d/n", num, num * num);

        num = num + 1;

    }

 

    return 0;

}

*/

///

/* wheat.c -- exponential growth */

/*                                                       // 棋盘赠大米,国王傻眼啦

#include <stdio.h>

#define SQUARES 64    // squares on a checkerboard  

#define CROP 1E15     // US wheat crop in grains    

int main(void)

{

    double current, total;

    int count = 1;

 

    printf("square     grains       total     ");

    printf("fraction of /n");

    printf("           added        grains      ");

    printf("US total/n");

    total = current = 1.0; // start with one grain  

    printf("%4d %13.2e %12.2e %12.2e/n", count, current,

           total, total/CROP);

    while (count < SQUARES)

    {

        count = count + 1;

        current = 2.0 * current;

                     // double grains on next square

        total = total + current;     // update total

        printf("%4d %13.2e %12.2e %12.2e/n", count, current,

                total, total/CROP);

     }

     printf("That's all./n");

  

     return 0;

}

*/

///

/* divide.c -- divisions we have known */

/*

#include <stdio.h>

int main(void)

{

     printf("integer division:  5/4    is %d /n", 5/4);

     printf("integer division:  6/3   is %d /n", 6/3);

     printf("integer division:  7/4   is %d /n", 7/4);

         printf("integer division:  7/-4   is %d /n", 7/-4);//print -1

         printf("integer division:  -7/4   is %d /n", -7/4);//print -1

     printf("floating division: 7./4. is %1.2f /n", 7./4.);

     printf("mixed division:    7./4  is %1.2f /n", 7./4);

    printf("mixed division:    -7./4  is %1.2f /n", -7./4); // print -1.75

         printf("mixed division:    7./-4  is %1.2f /n", 7./-4); //print -1.75

         printf("mixed division:    -7./-4  is %1.2f /n", -7./-4);

     return 0;

}

*/

///

// sizeof.c -- uses sizeof operator

// uses C99 %z modifier -- try %u or %lu if you lack %zd               //%z don't work

/*

#include <stdio.h>

int main(void)

{

    int n = 0;

    size_t intsize;

 

    intsize = sizeof (int);

    printf("n = %d, n has %u bytes; all ints have %u bytes./n",

         n, sizeof n, intsize );

        

    return 0;

}

*/

///

/* post_pre.c -- postfix vs prefix */

/*

#include <stdio.h>

int main(void)

{

    int a = 1, b = 1;

    int aplus, plusb;

 

    aplus = a++;   

    plusb = ++b;   

       printf("a   aplus   b   plusb /n");

    printf("%1d %5d %5d %5d/n", a, aplus, b, plusb);    // 2   1  2  2

  

    return 0;

}

*/

///

/* convert.c -- automatic type conversions */

/*

#include <stdio.h>

int main(void)

{

    char ch;

    int i;

    float fl;

 

    fl = i = ch = 'C';                                 

    printf("ch = %c, i = %d, fl = %2.2f/n", ch, i, fl);

    ch = ch + 1;                                      

    i = fl + 2 * ch;                                  

    fl = 2.0 * ch + i;                                 

    printf("ch = %c, i = %d, fl = %2.2f/n", ch, i, fl);

    ch = 5212205.17;                                    // print -                   still confused

    printf("Now ch = %c/n", ch);

 

    return 0;

}*/

///

 

/* pound.c -- defines a function with an argument   */

/*

#include <stdio.h>

void pound(int n);  

 

int main(void)

{

    int times = 5;

    char ch = '!';   // ASCII code is 33     

    float f = 6.0;

 

    pound(times);   

    pound(ch);       // char automatically -> int 

    pound((int) f);  // cast forces f -> int       

 

    return 0;

}

 

void pound(int n)   

{                   

    while (n-- > 0)

        printf("#");

    printf("/n");

}

*/

///

///

// chapter 06  C 控制语句:循环

/* summing.c -- sums integers entered interactively */

/*

#include <stdio.h>

int main(void)

{

    long num;

    long sum = 0L;     

    int status;

 

    printf("Please enter an integer to be summed ");

    printf("(q to quit): ");

    status = scanf("%ld", &num);

    while (status == 1) // == means "is equal to"  

    {

        sum = sum + num;

        printf("Please enter next integer (q to quit): ");

        status = scanf("%ld", &num);

    }

    printf("Those integers sum to %ld./n", sum);

 

     return 0;

}

*/

///

/* t_and_f.c -- true and false values in C */

/*

#include <stdio.h>

int main(void)

{

    int true_val, false_val;

 

    true_val = (10 > 2);  

    false_val = (10 == 2);

    printf("true = %d; false = %d /n", true_val, false_val);

 

    return 0;

}

*/

///

// boolean.c -- using a _Bool variable

/*

#include <stdio.h>

int main(void)

{

    long num;

    long sum = 0L; 

    int input_is_good;

 

    printf("Please enter an integer to be summed ");

    printf("(q to quit): ");

    input_is_good = (scanf("%ld", &num) == 1);

    while (input_is_good)

    {

        sum = sum + num;

        printf("Please enter next integer (q to quit): ");

        input_is_good = (scanf("%ld", &num) == 1);

    }

    printf("Those integers sum to %ld./n", sum);

 

    return 0;

}

*/

///

// sweetie1.c -- a counting loop

/*

#include <stdio.h>

int main(void)

{

    const int NUMBER = 22;

    int count = 1;                     // initialization

 

    while (count <= NUMBER)            // test

    {

        printf("Be my Valentine!/n");  // action

         

        count++;

      

       }

                printf(" the time of loop is %d/n",--count);

 

    return 0;

}

*/

///

// sweetie2.c -- a counting loop using for

/*

#include <stdio.h>

int main(void)

{

    const int NUMBER = 22;

    int count;

 

    for (count = 1; count <= NUMBER; count++)

        printf("Be my Valentine!/n");

 

      printf(" the time of loop is %d/n",--count);

 

    return 0;

}

*/

///

/* rows1.c -- uses nested loops */

/*

#include <stdio.h>

#define ROWS  6

#define CHARS 10

int main(void)

{

    int row;

    char ch;

 

    for (row = 0; row < ROWS; row++)            

       {

        for (ch = 'A'; ch < ('A' + CHARS); ch++)

            printf("%c", ch);

        printf("/n");

    }

   

    return 0;

}

*/

///

// rows2.c -- using dependent nested loops

/*

#include <stdio.h>

int main(void)

{

    const int ROWS = 6;

    const int CHARS = 6;

    int row;

    char ch;

 

    for (row = 0; row < ROWS; row++)

    {

        for (ch = ('A' + row);  ch < ('A' + CHARS); ch++)

            printf("%c", ch);

        printf("/n");

    }

   

    return 0;

}

*/

///

// scores_in.c -- uses loops for array processing

/*

#include <stdio.h>

#define SIZE 10

#define PAR 72

int main(void)

{

    int index, score[SIZE];

    int sum = 0;

    float average;

 

    printf("Enter %d golf scores:/n", SIZE);

    for (index = 0; index < SIZE; index++)

        scanf("%d", &score[index]);  // read in the ten scores

    printf("The scores read in are as follows:/n");

    for (index = 0; index < SIZE; index++)

        printf("%5d", score[index]); // verify input

    printf("/n");

    for (index = 0; index < SIZE; index++)

        sum += score[index];         // add them up

    average = (float) sum / SIZE;    // time-honored method

    printf("Sum of scores = %d, average = %.2f/n", sum, average);

    printf("That's a handicap of %.0f./n", average - PAR);

 

    return 0;

}

*/

///

// an answer to the question 16 at page 151

/*

#include<stdio.h>

 

void main()

{

       int year=0;

       double f;

       for(f=100;f>0;f=f-10)

       {

       printf("at the year %d , the money you have is %g /n",year,f);

              f=f+f*0.08;

              year++;

      

       }

 

       printf("at the year %d/n",year);

       printf("you have no money now!/n");

 

}

 

*/

///

///

//chapter 07 C 控制语句:分支与跳转

// colddays.c -- finds percentage of days below freezing

/*

#include <stdio.h>

int main(void)

{

    const int FREEZING = 0;

    float temperature;

    int cold_days = 0;

    int all_days = 0;

 

    printf("Enter the list of daily low temperatures./n");

    printf("Use Celsius, and enter q to quit./n");

    while (scanf("%f", &temperature) == 1)

    {

        all_days++;

        if (temperature < FREEZING)

            cold_days++;

    }

    if (all_days != 0)

        printf("%d days total: %.1f%% were below freezing./n",

               all_days, 100.0 * (float) cold_days / all_days);

    if (all_days == 0)

        printf("No data entered!/n");

 

    return 0;

}

*/

///

/* cypher1.c -- alters input, preserving spaces */

/*

#include <stdio.h>

#define SPACE ' '             // that's quote-space-quote

int main(void)

{

    char ch;

 

    ch = getchar();         

    while (ch != '/n')        //* while not end of line   

    {

        if (ch == SPACE)      //* leave the space         

            putchar(ch);      //* character unchanged     

        else

            putchar(ch + 1);  //* change other characters 

        ch = getchar();   

    }

    putchar(ch);          

    return 0;

}

*/

///

 

// cypher2.c -- alters input, preserving non-letters

/*

#include <stdio.h>

#include <ctype.h>            // for isalpha()

int main(void)

{

    char ch;

 

    while ((ch = getchar()) != '/n')

    {

        if (isalpha(ch))       // if a letter,

            putchar(ch + 1);  // change it

        else                  // otherwise,

            putchar(ch);      // print as is

    }

    putchar(ch);              // print the newline

  

    return 0;

}

*/

///

// chcount.c  -- use the logical AND operator

/*

#include <stdio.h>

#define PERIOD '.'

int main(void)

{

    int ch;

    int charcount = 0;

 

    while ((ch = getchar()) != PERIOD)

    {

        if (ch != '"' && ch != '/'')

             charcount++;

    }

    printf("There are %d non-quote characters./n", charcount);

 

    return 0;

}

*/

//

// wordcnt.c -- counts characters, words, lines

/*

#include <stdio.h>

#include <ctype.h>         // for isspace() 

#define STOP '|'

#define false 0

#define true 1

int main(void)

{

    char c;                 // read in character

    char prev;              // previous character read

    long n_chars = 0L;      // number of characters

    int n_lines = 0;         // number of lines

    int n_words = 0;        // number of words

    int p_lines = 0;        // number of partial lines

    int  inword = false;    // == true if c is in a word

 

    printf("Enter text to be analyzed (| to terminate):/n");

    prev = '/n';            // used to identify complete lines

    while ((c = getchar()) != STOP)

    {

        n_chars++;          // count characters

        if (c == '/n')

            n_lines++;      // count lines

        if (!isspace(c) && !inword)                          

        {

            inword = true;  // starting a new word

            n_words++;      // count word

        }

        if (isspace(c) && inword)

            inword = false; // reached end of word

        prev = c;           // save character value

    }

  

    if (prev != '/n')

        p_lines = 1;

    printf("characters = %ld, words = %d, lines = %d, ",

          n_chars, n_words, n_lines);

    printf("partial lines = %d/n", p_lines);

  

    return 0;

}

*/

/

/* paint.c -- uses conditional operator */

/*

#include <stdio.h>

#define COVERAGE 200       // square feet per paint can

int main(void)

{

    int sq_feet;

    int cans;

 

    printf("Enter number of square feet to be painted:/n");

    while (scanf("%d", &sq_feet) == 1)

    {

        cans = sq_feet / COVERAGE;

        cans += (sq_feet % COVERAGE == 0) ? 0 : 1;

        printf("You need %d %s of paint./n", cans,

                cans == 1 ? "can" : "cans");

        printf("Enter next value (q to quit):/n");

    }

 

    return 0;

}

*/

//

///

//chapter 08 字符输入/ 输出和输入确认

 

/* echo.c -- repeats input */

/*

#include <stdio.h>

int main(void)

{

    char ch;

 

    while ((ch = getchar()) != '#')

                  putchar(ch);

 

    printf("/n");

    return 0;

}

*/

//

/* echo_eof.c -- repeats input to end of file */

/*

#include <stdio.h>

int main(void)

{

    int ch;

 

    while ((ch = getchar()) != EOF)  //now you know how to end the program

        putchar(ch);

 

    return 0;

}

*/

//

// file_eof.c --open a file and display it

/*

#include <stdio.h>

#include <stdlib.h>  // for exit()

int main()

{

    int ch;

    FILE * fp;

    char fname[50];         // to hold the file name

 

    printf("Enter the name of the file: ");

    scanf("%s", fname);

    fp = fopen(fname, "r"); // open file for reading

    if (fp == NULL)         // attempt failed

    {

           printf("Failed to open file. Bye/n");        

           exit(1);             // quit program

    }

// getc(fp) gets a character from the open file

    while ((ch = getc(fp)) != EOF)

        putchar(ch);

    fclose(fp);             // close the file

    printf("/n");

    return 0;

}

*/

//

/* showchar2.c -- prints characters in rows and columns */

/*

#include <stdio.h>

void display(char cr, int lines, int width);

int main(void)

{

    int ch;             // character to be printed     

    int rows, cols;     // number of rows and columns  

 

    printf("Enter a character and two integers:/n");

    while ((ch = getchar()) != '/n')

    {

        if (scanf("%d %d",&rows, &cols) != 2)

            break;

        display(ch, rows, cols);

        while (getchar() !=  '/n')

            continue;

        printf("Enter another character and two integers;/n");

        printf("Enter a newline to quit./n");

    }

    printf("Bye./n");

  

    return 0;

}

 

void display(char cr, int lines, int width)

{

    int row, col;

 

    for (row = 1; row <= lines; row++)

    {

        for (col = 1; col <= width; col++)

             putchar(cr);

        putchar('/n');

       }

}

*/

//

 

/* checking.c -- validating input */

/*

#define true 1

#define false 0

#include <stdio.h>

// validate that input is an integer

int get_int(void);

// validate that range limits are valid

int bad_limits(int begin, int end, int low, int high);

// calculate the sum of the squares of the integers

// a through b

double sum_squares(int a, int b);

int main(void)

{

    const int MIN = -1000;  // lower limit to range

    const int MAX = +1000;  // upper limit to range

    int start;              // start of range

    int stop;               // end of range

    double answer;

  

    printf("This program computes the sum of the squares of "

           "integers in a range./nThe lower bound should not "

           "be less than -1000 and/nthe upper bound should not "

           "be more than +1000./nEnter the limits (enter 0 for "

           "both limits to quit):/nlower limit: ");

    start = get_int();

    printf("upper limit: ");

    stop = get_int();

    while (start !=0 || stop != 0)

    {

        if (bad_limits(start, stop, MIN, MAX))

            printf("Please try again./n");

        else

        {

            answer = sum_squares(start, stop);

             printf("The sum of the squares of the integers ");

            printf("from %d to %d is %g/n", start, stop, answer);

        }

        printf("Enter the limits (enter 0 for both "

               "limits to quit):/n");

        printf("lower limit: ");

         start = get_int();

        printf("upper limit: ");

        stop = get_int();

    }

    printf("Done./n");

  

    return 0;

}

 

int get_int(void)

{

    int input;

    char ch;

  

    while (scanf("%d", &input) != 1)

    {

        while ((ch = getchar()) != '/n')

            putchar(ch);            // dispose of bad input           // this function is very well,you know .

        printf(" is not an integer./nPlease enter an ");

        printf("integer value, such as 25, -178, or 3: ");

    }

  

    return input;

}

 

double sum_squares(int a, int b)

{

    double total = 0;

    int i;

  

    for (i = a; i <= b; i++)

        total += i * i;

  

    return total;

}

 

int bad_limits(int begin, int end, int low, int high)

{

    int not_good = false;

   

     if (begin > end)

    {

        printf("%d isn't smaller than %d./n", begin, end);

        not_good = true;

    }

    if (begin < low || end < low)

    {

        printf("Values must be %d or greater./n", low);

        not_good = true;

    }

    if (begin > high || end > high)

    {

        printf("Values must be %d or less./n", high);

        not_good = true;

    }

     

    return not_good;

}

*/

//

/* menuette.c -- menu techniques */

/*                                          // 小心空格的作用,假如在q 之前输入空格的话,要小心。

#include <stdio.h>

char get_choice(void);

char get_first(void);

int get_int(void);

void count(void);

int main(void)

{

    int choice;

    void count(void);

 

    while ( (choice = get_choice()) != 'q')

     {

        switch (choice)

        {

            case 'a' :  printf("Buy low, sell high./n");

                        break;

            case 'b' :  putchar('/a');  // ANSI

                        break;

            case 'c' :  count();

                         break;

            default  :  printf("Program error!/n");

                        break;

        }

    }

    printf("Bye./n");

   

    return 0;

}

 

void count(void)

{

    int n,i;

 

    printf("Count how far? Enter an integer:/n");

    n = get_int();

    for (i = 1; i <= n; i++)

        printf("%d/n", i);

    while ( getchar() != '/n')

        continue;

}

 

char get_choice(void)

{

    int ch;

 

    printf("Enter the letter of your choice:/n");

    printf("a. advice           b. bell/n");

    printf("c. count            q. quit/n");

    ch = get_first();

    while (  (ch < 'a' || ch > 'c') && ch != 'q')

    {

        printf("Please respond with a, b, c, or q./n");

        ch = get_first();

    }

   

    return ch;

}

 

char get_first(void)

{

    int ch;

 

    ch = getchar();

    while (getchar() != '/n')

        continue;

       

    return ch;

}

 

int get_int(void)

{

    int input;

    char ch;

   

    while (scanf("%d", &input) != 1)

    {

        while ((ch = getchar()) != '/n')

            putchar(ch);  // dispose of bad input

        printf(" is not an integer./nPlease enter an ");

        printf("integer value, such as 25, -178, or 3: ");

    }

   

    return input;

}

*/

//

/

//   chapter 09 函数

/* lesser.c -- finds the lesser of two evils */

/*

#include <stdio.h>

int imin(int, int);

 

int main(void)

{

    int evil1, evil2;

 

    printf("Enter a pair of integers (q to quit):/n");

    while (scanf("%d %d", &evil1, &evil2) == 2)

    {

        printf("The lesser of %d and %d is %d./n",

            evil1, evil2, imin(evil1,evil2));

        printf("Enter a pair of integers (q to quit):/n");

    }

    printf("Bye./n");

 

    return 0;

}

 

int imin(int n,int m)

{

    int min;

 

    if (n < m)

        min = n;

    else

        min = m;

 

    return min;

}

 

 

*/

 

/* recur.c -- recursion illustration */

/*                                                        // don't understand how it works

#include <stdio.h>

void up_and_down(int);

 

int main(void)

{

    up_and_down(1);

    return 0;

}

 

void up_and_down(int n)

{

    printf("Level %d: n location %p/n", n, &n);

    if (n < 4)

         up_and_down(n+1);

    printf("LEVEL %d: n location %p/n", n, &n);

}

 

*/

 

//

/* binary.c -- prints integer in binary form */

/*

#include <stdio.h>

void to_binary(unsigned long n);

 

int main(void)

{

    unsigned long number;

    printf("Enter an integer (q to quit):/n");

    while (scanf("%ul", &number) == 1)

    {

        printf("Binary equivalent: ");

        to_binary(number);

        putchar('/n');

        printf("Enter an integer (q to quit):/n");

    }

    printf("Done./n");

 

    return 0;

}

 

void to_binary(unsigned long n)   //* recursive function

{

    int r;

 

    r = n % 2;

    if (n >= 2)

       to_binary(n / 2);

    putchar('0' + r);

 

    return;

}

*/

//

//

//chapter 10  数组和指针

 

/* some_data.c -- partially initialized array */         // 未赋值的元素被初始化为0

/*

#include <stdio.h>

#define SIZE 4

int main(void)

{

    int some_data[SIZE] = {1492, 1066};  

    int i;

 

    printf("%2s%14s/n",

           "i", "some_data[i]");

    for (i = 0; i < SIZE; i++)

        printf("%2d%14d/n", i, some_data[i]);

 

    return 0;

}

*/

//

// designate.c -- use designated initializers

/*                                                                 //here has some problem ,you should take care ,it doesn't cordinate with the textbook

#include <stdio.h>

#define MONTHS 12

int main(void)

{

    int days[MONTHS] = {31,28,days[4] = 28,30,31, days[1]= 29};

    int i;

 

    for (i = 0; i < MONTHS; i++)

        printf("%2d  %d/n", i + 1, days[i]);

  

    return 0;

}

*/

//

// bounds.c -- exceed the bounds of an array

/*

#include <stdio.h>

#define SIZE 4

int main(void)

{

    int value1 = 44;

    int arr[SIZE];

    int value2 = 88;

    int i;

 

    printf("value1 = %d, value2 = %d/n", value1, value2);

    for (i = -1; i <= SIZE; i++)

        arr[i] = 2 * i + 1;

       

    for (i = -1; i < 7; i++)

         printf("%2d  %d/n", i , arr[i]);

    printf("value1 = %d, value2 = %d/n", value1, value2);

 

    return 0;

}

*/

/* rain.c  -- finds yearly totals, yearly average, and monthly

                 average for several years of rainfall data */

/*

#include <stdio.h>

#define MONTHS 12    // number of months in a year

#define YEARS   5    // number of years of data

int main(void)

{

  // initializing rainfall data for 2000 - 2004

    const float rain[YEARS][MONTHS] =

    {

        {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},

        {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},

        {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},

        {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},

        {7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2}

    };

    int year, month;

    float subtot, total;

 

    printf(" YEAR    RAINFALL  (inches)/n");

    for (year = 0, total = 0; year < YEARS; year++)

    {             // for each year, sum rainfall for each month

        for (month = 0, subtot = 0; month < MONTHS; month++)

            subtot += rain[year][month];

        printf("%5d %15.1f/n", 2000 + year, subtot);

        total += subtot; // total for all years

     }

    printf("/nThe yearly average is %.1f inches./n/n",

            total/YEARS);

    printf("MONTHLY AVERAGES:/n/n");

    printf(" Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct ");

    printf(" Nov  Dec/n");

 

    for (month = 0; month < MONTHS; month++)

    {             // for each month, sum rainfall over years

        for (year = 0, subtot =0; year < YEARS; year++)

            subtot += rain[year][month];

        printf("%4.1f ", subtot/YEARS);

    }

    printf("/n");

 

    return 0;

}

 

*/

//

/*

// pnt_add.c -- pointer addition

#include <stdio.h>

#define SIZE 4

int main(void)

{

    short dates [SIZE];

    short * pti;

    short index;

    double bills[SIZE];

    double * ptf;

 

    pti = dates;    // assign address of array to pointer

     ptf = bills;

    printf("%23s %10s/n", "short", "double");

    for (index = 0; index < SIZE; index ++)

        printf("pointers + %d: %10p %10p/n",

                index, pti + index, ptf + index);

 

    return 0;

}

*/

//

 

/* day_mon3.c -- uses pointer notation */

/*

#include <stdio.h>

#define MONTHS 12

 

int main(void)

{

    int days[MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31};

    int index;

 

    for (index = 0; index < MONTHS; index++)

        printf("Month %2d has %d days./n", index +1,

               *(days + index));   // same as days[index]

 

    return 0;

}

*/

//

 

// sum_arr1.c -- sums the elements of an array

// use %u or %lu if %zd doesn't work

/*

#include <stdio.h>

#define SIZE 10

int sum(int ar[], int n);

int main(void)

{

    int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20};

    long answer;

 

    answer = sum(marbles, SIZE);

    printf("The total number of marbles is %ld./n", answer);

     printf("The size of marbles is %u bytes./n",

          sizeof marbles);

   

    return 0;

}

 

int sum(int ar[], int n)     // how big an array?

{

    int i;

    int total = 0;

 

    for( i = 0; i < n; i++)

        total += ar[i];

    printf("The size of ar is %u bytes./n", sizeof ar);

   

    return total;

}

*/

//

 

/* sum_arr2.c -- sums the elements of an array */

/*

#include <stdio.h>

#define SIZE 10

int sump(int * start, int * end);

int main(void)

{

     int marbles[SIZE] = {20,10,5,39,4,16,19,26,31,20};

    long answer;

 

    answer = sump(marbles, marbles + SIZE);

    printf("The total number of marbles is %ld./n", answer);

 

    return 0;

}

 

// use pointer arithmetic  

int sump(int * start, int * end)

{

    int total = 0;

 

    while (start < end)

    {

        total += *start;

        start++;       

       }

 

    return total;

}

 

*/

//

 

/* order.c -- precedence in pointer operations */

/*

#include <stdio.h>

int data[2] = {100, 200};

int moredata[2] = {300, 400};

int main(void)

{

    int * p1, * p2, * p3;

 

    p1 = p2 = data;

    p3 = moredata;

    printf("  *p1 = %d,   *p2 = %d,     *p3 = %d/n",

              *p1     ,   *p2     ,     *p3);

    printf("*p1++ = %d, *++p2 = %d, (*p3)++ = %d/n",

            *p1++     , *++p2     , (*p3)++);

    printf("  *p1 = %d,   *p2 = %d,     *p3 = %d/n",

              *p1     ,   *p2     ,     *p3);

 

    return 0;

}

 

*/

//

 

/* arf.c -- array functions */

/*

#include <stdio.h>

#define SIZE 5

void show_array(const double ar[], int n);

void mult_array(double ar[], int n, double mult);

int main(void)

{

    double dip[SIZE] = {20.0, 17.66, 8.2, 15.3, 22.22};

 

    printf("The original dip array:/n");

    show_array(dip, SIZE);

    mult_array(dip, SIZE, 2.5);

    printf("The dip array after calling mult_array():/n");

    show_array(dip, SIZE);

 

    return 0;

}

 

void show_array(const double ar[], int n)

{

    int i;

 

    for (i = 0; i < n; i++)

        printf("%8.3f ", ar[i]);

    putchar('/n');

}

 

void mult_array(double ar[], int n, double mult)

{

    int i;

 

    for (i = 0; i < n; i++)

        ar[i] *= mult;

}

 

*/

//

 

/* zippo1.c --  zippo info */

/*

#include <stdio.h>

int main(void)

{

    int zippo[4][2] = { {2,4}, {6,8}, {1,3}, {5, 7} };

   

    printf("   zippo = %p,    zippo + 1 = %p/n",

               zippo,         zippo + 1);

    printf("zippo[0] = %p, zippo[0] + 1 = %p/n",

            zippo[0],      zippo[0] + 1);

    printf("  *zippo = %p,   *zippo + 1 = %p/n",

              *zippo,        *zippo + 1);

    printf("zippo[0][0] = %d/n", zippo[0][0]);

    printf("  *zippo[0] = %d/n", *zippo[0]);

    printf("    **zippo = %d/n", **zippo);

    printf("      zippo[2][1] = %d/n", zippo[2][1]);

    printf("*(*(zippo+2) + 1) = %d/n", *(*(zippo+2) + 1));

 

    return 0;

}

*/

//

 

/* zippo2.c --  zippo info via a pointer variable */

/*

#include <stdio.h>

int main(void)

{

    int zippo[4][2] = { {2,4}, {6,8}, {1,3}, {5, 7} };

    int (*pz)[2];

    pz = zippo;

   

    printf("   pz = %p,    pz + 1 = %p/n",

               pz,         pz + 1);

    printf("pz[0] = %p, pz[0] + 1 = %p/n",

            pz[0],      pz[0] + 1);

    printf("  *pz = %p,   *pz + 1 = %p/n",

              *pz,        *pz + 1);

    printf("pz[0][0] = %d/n", pz[0][0]);

    printf("  *pz[0] = %d/n", *pz[0]);

    printf("    **pz = %d/n", **pz);

    printf("       pz[2][1] = %d/n", pz[2][1]);

    printf("*(*(pz+2) + 1) = %d/n", *(*(pz+2) + 1));

   

    return 0;

}

 

*/

/

 

/*

// array2d.c -- functions for 2d arrays

#include <stdio.h>

#define ROWS 3

#define COLS 4

void sum_rows(int ar[][COLS], int rows);

void sum_cols(int [][COLS], int );    // ok to omit names

int sum2d(int (*ar)[COLS], int rows); // another syntax

int main(void)

{

     int junk[ROWS][COLS] = {

            {2,4,6,8},

            {3,5,7,9},

             {12,10,8,6}

     };

    

     sum_rows(junk, ROWS);

     sum_cols(junk, ROWS);

     printf("Sum of all elements = %d/n", sum2d(junk, ROWS));

    

     return 0;

}

 

void sum_rows(int ar[][COLS], int rows)

{

    int r;

    int c;

    int tot;

 

     for (r = 0; r < rows; r++)

    {

        tot = 0;

        for (c = 0; c < COLS; c++)

            tot += ar[r][c];

        printf("row %d: sum = %d/n", r, tot);

    }

}

 

void sum_cols(int ar[][COLS], int rows)

{

    int r;

    int c;

    int tot;

 

    for (c = 0; c < COLS; c++)

    {

        tot = 0;

        for (r = 0; r < rows; r++)

            tot += ar[r][c];

        printf("col %d: sum = %d/n", c, tot);

    }

}

 

int sum2d(int ar[][COLS], int rows)

{

    int r;

    int c;

    int tot = 0;

 

    for (r = 0; r < rows; r++)

        for (c = 0; c < COLS; c++)

            tot += ar[r][c];

   

    return tot;

}

 

*/

//vararr2d.c -- functions using VLAs                       //vc6.0 不支持变长数组这个新特性

/*

#include <stdio.h>

#define ROWS 3

#define COLS 4

int sum2d(int rows, int cols, int ar[rows][cols]);

int main(void)

{

     int i, j;

     int rs = 3;

     int cs = 10;

     int junk[ROWS][COLS] = {

            {2,4,6,8},

            {3,5,7,9},

            {12,10,8,6}

     };

    

     int morejunk[ROWS-1][COLS+2] = {

            {20,30,40,50,60,70},

            {5,6,7,8,9,10}

     };

    

     int varr[rs][cs];  // VLA

    

     for (i = 0; i < rs; i++)

         for (j = 0; j < cs; j++)

              varr[i][j] = i * j + j;

 

     printf("3x5 array/n");

     printf("Sum of all elements = %d/n",

             sum2d(ROWS, COLS, junk));

 

     printf("2x6 array/n");

     printf("Sum of all elements = %d/n",

             sum2d(ROWS-1, COLS+2, morejunk));

 

     printf("3x10 VLA/n");

     printf("Sum of all elements = %d/n",

             sum2d(rs, cs, varr));

 

     return 0;

}

 

// function with a VLA parameter

int sum2d(int rows, int cols, int ar[rows][cols])

{

    int r;

    int c;

    int tot = 0;

 

    for (r = 0; r < rows; r++)

        for (c = 0; c < cols; c++)

            tot += ar[r][c];

           

    return tot;

}

*/

//

/*

// flc.c -- funny-looking constants

#include <stdio.h>

#define COLS 4

int sum2d(int ar[][COLS], int rows);

int sum(int ar[], int n);

 

int main(void)

{

     int total1, total2, total3;

     int * pt1;

     int (*pt2)[COLS];

 

     pt1 = (int [2]){10, 20};                                    // 此种表示方法是复合文字,这里不支持。

     pt2 = (int [2][COLS]){ {1,2,3,-9}, {4,5,6,-8} };

 

     total1 = sum(pt1, 2);

     total2 = sum2d(pt2, 2);

     total3 = sum((int []){4,4,4,5,5,5}, 6);

     printf("total1 = %d/n", total1);

     printf("total2 = %d/n", total2);

     printf("total3 = %d/n", total3);

    

     return 0;

}

 

int sum(int ar[], int n)

{

    int i;

    int total = 0;

 

    for( i = 0; i < n; i++)

        total += ar[i];

       

    return total;

}

 

int sum2d(int ar[][COLS], int rows)

{

    int r;

    int c;

    int tot = 0;

 

    for (r = 0; r < rows; r++)

        for (c = 0; c < COLS; c++)

            tot += ar[r][c];

           

    return tot;

}

*/

//

// strings.c -- stringing the user along

/*

#include <stdio.h>

#define MSG "You must have many talents. Tell me some."

                          // a symbolic string constant

#define LIM  5

#define LINELEN 81        // maximum string length + 1

int main(void)

{

    char name[LINELEN];

    char talents[LINELEN];

    int i;

                           // initializing a dimensioned

                          // char array      

    const char m1[40] = "Limit yourself to one line's worth.";

                          // letting the compiler compute the

                          // array size    

    const char m2[] = "If you can't think of anything, fake it.";

                          // initializing a pointer 

    const char *m3 = "/nEnough about me -- what's your name?";

                          // initializing an array of

                           // string pointers        

    const char *mytal[LIM] = {  // array of 5 pointers

          "Adding numbers swiftly",

          "Multiplying accurately", "Stashing data",

          "Following instructions to the letter",

          "Understanding the C language"

          };

 

    printf("Hi! I'm Clyde the Computer."

           " I have many talents./n");

    printf("Let me tell you some of them./n");

    puts("What were they? Ah, yes, here's a partial list.");

    for (i = 0; i < LIM; i++)

        puts(mytal[i]);   // print list of computer talents

    puts(m3);

    gets(name);

    printf("Well, %s, %s/n", name, MSG);

    printf("%s/n%s/n", m1, m2);

    gets(talents);

    puts("Let's see if I've got that list:");

    puts(talents);

    printf("Thanks for the information, %s./n", name);

 

    return 0;

}

*/

/

 

/* quotes.c -- strings as pointers */

/*

#include <stdio.h>

int main(void)

{

    printf("%s, %#p, %c/n", "We", "are", *"space farers");

   

    return 0;

}

*/

///

 

/* p_and_s.c -- pointers and strings */

/*

#include <stdio.h>

int main(void)

{

    const char * mesg = "Don't be a fool!";

    const char * copy;

 

    copy = mesg;

     printf("%s/n", copy);

    printf("mesg = %s; &mesg = %p; value = %p/n",    //value 指针的值即该指针存放的地址 相等

            mesg, &mesg, mesg);

    printf("copy = %s; &copy = %p; value = %p/n",    //just confused

            copy, &copy, copy);

 

    return 0;

}

*/

 

/* name3.c -- reads a name using fgets() */

/*

#include <stdio.h>

#define MAX 81

int main(void)

{

    char name[MAX];

    char * ptr;

 

    printf("Hi, what's your name?/n");            

    ptr = fgets(name, MAX, stdin);                  //fgets() 将换行符存储到字符串中

    printf("%s? Ah! %s!/n", name, ptr);

   

    return 0;

}

 

*/

 

/* scan_str.c -- using scanf() */

/*

#include <stdio.h>

int main(void)

{

    char name1[11], name2[11];

    int count;

 

    printf("Please enter 2 names./n");

    count = scanf("%5s %10s",name1, name2);           //you should take care

    printf("I read the %d names %s and %s./n",

           count, name1, name2);

   

    return 0;

}

 

 

*/

/

 

/* put_out.c -- using puts() */

/*

#include <stdio.h>

#define DEF "I am a #defined string."

int main(void)

{

    char str1[80] = "An array was initialized to me.";

    const char * str2 = "A pointer was initialized to me.";

 

    puts("I'm an argument to puts().");

    puts(DEF);

    puts(str1);

     puts(str2);

    puts(&str1[5]);

    puts(str2+4);

 

    return 0;

}

 

*/

//

 

/*

//put_put.c -- user-defined output functions

#include <stdio.h>

void put1(const char *);

int put2(const char *);

 

int main(void)

{

     put1("If I'd as much money");

    put1(" as I could spend,/n");

    printf("I count %d characters./n",

           put2("I never would cry old chairs to mend."));    //take care of here

          

    return 0;

}

 

void put1(const char * string)

{

    while (*string)  // same as *string != '/0'

        putchar(*string++);

}

 

int put2(const char * string)

{

    int count = 0;

    while (*string)

    {

        putchar(*string++);

        count++;

    }

    putchar('/n');

   

    return(count);

}

*/

///

 

/* test_fit.c -- try the string-shrinking function */

/*

#include <stdio.h>

#include <string.h> // contains string function prototypes

void fit(char *, unsigned int);

 

int main(void)

{

    char mesg[] = "Things should be as simple as possible,"

                  " but not simpler.";

 

    puts(mesg);

    fit(mesg,38);

    puts(mesg);

    puts("Let's look at some more of the string.");

    puts(mesg + 39);

 

    return 0;

}

 

void fit(char *string, unsigned int size)

{

    if (strlen(string) > size)

        *(string + size) = '/0';

}

*/

 

 

 

/* str_cat.c -- joins two strings */

/*

#include <stdio.h>

#include <string.h> 

#define SIZE 80

int main(void)

{

    char flower[SIZE];

    char addon[] = "s smell like old shoes.";

 

    puts("What is your favorite flower?");

    gets(flower);

    strcat(flower, addon);

    puts(flower);

    puts(addon);

  

    return 0;

}

*/

//

 

/* join_chk.c -- joins two strings, check size first */

/*

#include <stdio.h>

#include <string.h>

#define SIZE 30

#define BUGSIZE 13

int main(void)

{

    char flower[SIZE];

    char addon[] = "s smell like old shoes.";

    char bug[BUGSIZE];

    int available;

 

    puts("What is your favorite flower?");

    gets(flower);

    if ((strlen(addon) + strlen(flower) + 1) <= SIZE)

        strcat(flower, addon);

    puts(flower);

    puts("What is your favorite bug?");

    gets(bug);

    available = BUGSIZE - strlen(bug) - 1; 

   printf("length of bug %d/n",strlen(bug));

         printf(" length of available %d/n",available);                          

    strncat(bug, addon, available);                               //have some problem here

    puts(bug);

  

    return 0;

}

*/

//

 

/* compare.c -- this will work */

/*

#include <stdio.h>

#include <string.h>  

#define ANSWER "Grant"

#define MAX 40

int main(void)

{

    char try[MAX];

 

    puts("Who is buried in Grant's tomb?");

     gets(try);

    while (strcmp(try,ANSWER) != 0)                       //here is the critical

    {

        puts("No, that's wrong. Try again.");

        gets(try);

    }

    puts("That's right!");

   

    return 0;

}

 

*/

/

/* compback.c -- strcmp returns */

/*

#include <stdio.h>

#include <string.h>

int main(void)

{

 

    printf("strcmp(/"A/", /"A/") is ");

    printf("%d/n", strcmp("A", "A"));

 

    printf("strcmp(/"A/", /"B/") is ");

    printf("%d/n", strcmp("A", "B"));

 

    printf("strcmp(/"B/", /"A/") is ");

    printf("%d/n", strcmp("B", "A"));

 

    printf("strcmp(/"C/", /"A/") is ");

    printf("%d/n", strcmp("C", "A"));

 

    printf("strcmp(/"Z/", /"a/") is ");

    printf("%d/n", strcmp("Z", "a"));

   

    printf("strcmp(/"apples/", /"apple/") is ");

    printf("%d/n", strcmp("apples", "apple"));

 

    return 0;

}

*/

/

 

/* quit_chk.c -- beginning of some program */

/*

#include <stdio.h>

#include <string.h>

#define SIZE 81

#define LIM 100

#define STOP "quit"

int main(void)

{

    char input[LIM][SIZE];

    int ct = 0;

 

    printf("Enter up to %d lines (type quit to quit):/n", LIM);

   // while (ct < LIM && gets(input[ct]) != NULL && strcmp(input[ct],STOP) != 0)

    while(ct< LIM && gets(input[ct])!=NULL && input[ct][0]!='/0')

       {

        ct++;

    }

    printf("%d strings entered/n", ct);

 

    return 0;

}

*/

///

/* copy2.c -- strcpy() demo */                           // read it carefully

/*

#include <stdio.h>

#include <string.h>   

#define WORDS  "beast"

#define SIZE 40

 

int main(void)

{

    const char * orig = WORDS;

    char copy[SIZE] = "Be the best that you can be.";

    char * ps;

 

    puts(orig);

    puts(copy);

    ps = strcpy(copy + 7, orig);

    puts(copy);

    puts(ps);

  

    return 0;

}

*/

/

 

 

/* copy3.c -- strncpy() demo */

/*

#include <stdio.h>

#include <string.h>

#define SIZE 40

#define TARGSIZE 7

#define LIM 5

int main(void)

{

    char qwords[LIM][TARGSIZE];

    char temp[SIZE];

    int i = 0;

  

    printf("Enter %d words beginning with q:/n", LIM);

    while (i < LIM && gets(temp))

    {

        if (temp[0] != 'q')

            printf("%s doesn't begin with q!/n", temp);

        else

        {

            strncpy(qwords[i], temp, TARGSIZE - 1);

            qwords[i][TARGSIZE - 1] = '/0';

            i++;

        }

    }

    puts("Here are the words accepted:");

    for (i = 0; i < LIM; i++)

         puts(qwords[i]);

  

    return 0;

}

*/

//

 

/* format.c -- format a string */

/*

#include <stdio.h>

#define MAX 20

 

int main(void)

{

    char first[MAX];

    char last[MAX];

    char formal[2 * MAX + 10];

    double prize;

 

    puts("Enter your first name:");

    gets(first);

    puts("Enter your last name:");

    gets(last);

    puts("Enter your prize money:");

    scanf("%lf", &prize);

    sprintf(formal, "%s, %-19s: $%6.2f/n", last, first, prize);         // sprintf()  you should take care of the function

    puts(formal);

   

    return 0;

}

*/

///

 

/* repeat.c -- main() with arguments */

/*

#include <stdio.h>

int main(int argc, char *argv[])

{

    int count;

 

    printf("The command line has %d arguments:/n", argc - 1);        // just test it in WIN-TC

    for (count = 1; count < argc; count++)

        printf("%d: %s/n", count, argv[count]);

    printf("/n");

  

    return 0;

}

*/

///

 

/* strcnvt.c -- try strtol()  */

/*

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

    char number[30];

    char * end;

    long value;

 

    puts("Enter a number (empty line to quit):");

    while(gets(number) && number[0] != '/0')

    {

        value = strtol(number, &end, 10);  // base 10

        printf("value: %ld, stopped at %s (%d)/n",

                      value, end, *end);

        value = strtol(number, &end, 16);  // base 16

        printf("value: %ld, stopped at %s (%d)/n",

                      value, end, *end);

        puts("Next number:");

    }

    puts("Bye!/n");

   

    return 0;

}

*/

//

//

// chapter 12 存储类、链接和内存管理

/* hiding.c -- variables in blocks */

/*

#include <stdio.h>

int main()

{

    int x = 30;    

   

    printf("x in outer block: %d/n", x);

    {

        int x = 77;

        printf("x in inner block: %d/n", x);

    }

    printf("x in outer block: %d/n", x);

    while (x++ < 33)

    {

        int x = 100;

        x++;

        printf("x in while loop: %d/n", x);

    }

    printf("x in outer block: %d/n", x);    // will print 34 not 33

   

    return 0;

}

*/

///

 

/* global.c  -- uses an external variable */

/*

#include <stdio.h>

int units = 0;         // an external variable   

void critic(void);

int main(void)

{

   // extern int units;      // an optional redeclaration

 

    printf("How many pounds to a firkin of butter?/n");

    scanf("%d", &units);

    while ( units != 56)

        critic();

    printf("You must have looked it up!/n");

  

    return 0;

}

 

void critic(void)

{

    // optional redeclaration omitted

    printf("No luck, chummy. Try again./n");

    scanf("%d", &units);

}

 

*/

 

//

 

 

 

/* dyn_arr.c -- dynamically allocated array */

/*

#include <stdio.h>

#include <stdlib.h>

 

int main(void)

{

    double * ptd;

    int max;

    int number;

    int i = 0;

 

    puts("What is the maximum number of type double entries?");

    scanf("%d", &max);

    ptd = (double *) malloc(max * sizeof (double));

    if (ptd == NULL)

    {

        puts("Memory allocation failed. Goodbye.");

        exit(EXIT_FAILURE);

     }

    // ptd now points to an array of max elements

    puts("Enter the values (q to quit):");

    while (i < max && scanf("%lf", &ptd[i]) == 1)

        ++i;

    printf("Here are your %d entries:/n", number = i);

    for (i = 0; i < number; i++)

    {

        printf("%7.2f ", ptd[i]);

        if (i % 7 == 6)

            putchar('/n');

    }

    if (i % 7 != 0)

        putchar('/n');

    puts("Done.");

    free(ptd);

 

    return 0;

}

*/

//

//

//

//chapter 13 文件输入与输出

 

/* count.c -- using standard I/O */

/*

#include <stdio.h>

 

#include <stdlib.h> // ANSI C exit() prototype

int main(int argc, char *argv[])

{

    int ch;         // place to store each character as read

    FILE *fp;       // "file pointer"

    long count = 0;

 

    if (argc != 2)

    {

        printf("Usage: %s filename/n", argv[0]);

        exit(1);

    }

    if ((fp = fopen(argv[1], "r")) == NULL)

    {

        printf("Can't open %s/n", argv[1]);

        exit(1);

    }

    while ((ch = getc(fp)) != EOF)

    {

       putc(ch,stdout);  // same as putchar(ch);

       count++;

    }

    fclose(fp);

    printf("File %s has %ld characters/n", argv[1], count);

   

    return 0;

}

*/

//

 

/* parrot.c -- using fgets() and fputs() */

/*

#include <stdio.h>

#define MAXLINE 20

int main(void)

{

    char line[MAXLINE];

 

    while (fgets(line, MAXLINE, stdin) != NULL &&

             line[0] != '/n')

       fputs(line, stdout);

    return 0;

}

*/

//

 

 

/* reverse.c -- displays a file in reverse order */

/*

#include <stdio.h>

#include <stdlib.h>

#define CNTL_Z '/032'   // eof marker in DOS text files

#define SLEN 50

int main(void)

{

    char file[SLEN];

    char ch;

    FILE *fp;

    long count, last;

 

    puts("Enter the name of the file to be processed:");

    gets(file);

    if ((fp = fopen(file,"rb")) == NULL)

    {                      // read-only and binary modes

        printf("reverse can't open %s/n", file);

        exit(1);

    }

   

    fseek(fp, 0L, SEEK_END);        //go to end of file

    last = ftell(fp);

// if SEEK_END not supported, use this instead         

//  last = 0;

//    while (getc(fp) != EOF)

//        last++;

 

    for (count = last- 1; count >= 0; count--)

    {

        fseek(fp, count, SEEK_SET); // go backward    

        ch = getc(fp);

    // for DOS, works with UNIX

        if (ch != CNTL_Z && ch != '/r')

            putchar(ch);

    // for Macintosh         

    //  if (ch == '/r')

     //       putchar('/n');

    //     else

    //         putchar(ch)

   

   }

   putchar('/n');

   fclose(fp);

  

   return 0;

}

*/

//

//

 

//chapter 14  结构和其他数据形式

 

/* book.c -- one-book inventory */

/*

#include <stdio.h>

#define MAXTITL  41      // maximum length of title + 1       

#define MAXAUTL  31      // maximum length of author's name + 1

 

struct book {            // structure template: tag is book    

    char title[MAXTITL];

    char author[MAXAUTL];

    float value;

};                       // end of structure template         

 

int main(void)

{

    struct book library; // declare library as a book variable

   

    printf("Please enter the book title./n");

    gets(library.title); // access to the title portion     

    printf("Now enter the author./n");

    gets(library.author);

    printf("Now enter the value./n");

    scanf("%f", &library.value);

    printf("%s by %s: $%.2f/n",library.title,

          library.author, library.value);

    printf("%s: /"%s/" ($%.2f)/n", library.author,

          library.title, library.value);

    printf("Done./n");

         

    return 0;

}

 

*/

//

 

/* manybook.c -- multiple book inventory */

/*

#include <stdio.h>

#define MAXTITL   40

#define MAXAUTL   40

#define MAXBKS   100            

 

struct book {                  

    char title[MAXTITL];

    char author[MAXAUTL];

    float value;

};

 

int main(void)

{

    struct book library[MAXBKS];

    int count = 0;

    int index;

 

     printf("Press [enter] at the start of a line to stop./n");

         printf("Please enter the book title./n");

  

    while (count < MAXBKS && gets(library[count].title) != NULL

                           && library[count].title[0] != '/0')

    {

        printf("Now enter the author./n");

        gets(library[count].author);

        printf("Now enter the value./n");

        scanf("%f", &library[count++].value);

        while (getchar() != '/n')

            continue;        

        if (count < MAXBKS)

        printf("Enter the next title./n");

    }

   

    if (count > 0)

    {

        printf("Here is the list of your books:/n");

        for (index = 0; index < count; index++)

         printf("%s by %s: $%.2f/n", library[index].title,

            library[index].author, library[index].value);

    }

    else

    printf("No books? Too bad./n");

   

    return 0;

}

*/

//

 

/* booksave.c -- saves structure contents in a file */

/*

#include <stdio.h>

#include <stdlib.h>

#define MAXTITL   40

#define MAXAUTL   40

#define MAXBKS   10          

 

struct book {                 

    char title[MAXTITL];

    char author[MAXAUTL];

    float value;

};

 

int main(void)

{

    struct book library[MAXBKS]; // array of structures    

    int count = 0;

    int index, filecount;

    FILE * pbooks;

    int size = sizeof (struct book);

 

    if ((pbooks = fopen("book.dat", "a+b")) == NULL)

    {

        fputs("Can't open book.dat file/n",stderr);

        exit(1);

    }

   

    rewind(pbooks);            // go to start of file    

    while (count < MAXBKS &&  fread(&library[count], size,

                1, pbooks) == 1)

    {

        if (count == 0)

             puts("Current contents of book.dat:");

        printf("%s by %s: $%.2f/n",library[count].title,

            library[count].author, library[count].value);

        count++;

    }

    filecount = count;

    if (count == MAXBKS)

    {

        fputs("The book.dat file is full.", stderr);

        exit(2);

    }

   

    puts("Please add new book titles.");

    puts("Press [enter] at the start of a line to stop.");

    while (count < MAXBKS && gets(library[count].title) != NULL

                          && library[count].title[0] != '/0')

    {

        puts("Now enter the author.");

        gets(library[count].author);

        puts("Now enter the value.");

        scanf("%f", &library[count++].value);

        while (getchar() != '/n')

            continue;                 // clear input line

         if (count < MAXBKS)

             puts("Enter the next title.");

    }

   

    if (count > 0)

    {     

        puts("Here is the list of your books:");

        for (index = 0; index < count; index++)

            printf("%s by %s: $%.2f/n",library[index].title,

                   library[index].author, library[index].value);

        fwrite(&library[filecount], size, count - filecount,

                pbooks);

    }

    else

    puts("No books? Too bad./n");

   

     puts("Bye./n");

    fclose(pbooks);

   

    return 0;

}

*/

//

/*

// func_ptr.c -- uses function pointers

#include <stdio.h>

#include <string.h>

#include <ctype.h>

 

char showmenu(void);

void eatline(void);     // read through end of line   

void show(void (* fp)(char *), char * str);

void ToUpper(char *);   // convert string to uppercase

void ToLower(char *);   // convert string to uppercase

void Transpose(char *); // transpose cases            

void Dummy(char *);     // leave string unaltered     

 

int main(void)

{

    char line[81];

    char copy[81];

    char choice;

    void (*pfun)(char *); // points a function having a

                          // char * argument and no   

                           // return value             

    puts("Enter a string (empty line to quit):");

    while (gets(line) != NULL && line[0] != '/0')

    {

        while ((choice = showmenu()) != 'n')

        {

            switch (choice   )  // switch sets pointer

             {

                case 'u' : pfun = ToUpper;   break;

                case 'l' : pfun = ToLower;   break;

                case 't' : pfun = Transpose; break;

                case 'o' : pfun = Dummy;     break;

            }

            strcpy(copy, line);// make copy for show()

            show(pfun, copy);  // use selected function

        }

        puts("Enter a string (empty line to quit):");

    }

    puts("Bye!");

   

    return 0;

}

 

char showmenu(void)

{

    char ans;

    puts("Enter menu choice:");

    puts("u) uppercase       l) lowercase");

    puts("t) transposed case o) original case");

    puts("n) next string");

    ans = getchar();    // get response          

    ans = tolower(ans); // convert to lowercase  

    eatline();           // dispose of rest of line

    while (strchr("ulton", ans) == NULL)

    {

        puts("Please enter a u, l, t, o, or n:");

        ans = tolower(getchar());

        eatline();

    }

   

    return ans;

}

 

void eatline(void)

{

    while (getchar() != '/n')

        continue;

}

 

void ToUpper(char * str)

{

    while (*str)

    {

        *str = toupper(*str);

        str++;

    }

}

 

void ToLower(char * str)

{

    while (*str)

    {

        *str = tolower(*str);

        str++;

    }

}

void Transpose(char * str)

{

    while (*str)

    {

        if (islower(*str))

            *str = toupper(*str);

        else if (isupper(*str))

            *str = tolower(*str);

        str++;

    }

}

 

void Dummy(char * str)

{

    // leaves string unchanged

}

 

void show(void (* fp)(char *), char * str)

{

    (*fp)(str); // apply chosen function to str

    puts(str);  // display result

}

*/

//

//

//chapter 15

 

/* binbit.c -- using bit operations to display binary */

/*

#include <stdio.h>

char * itobs(int, char *);

void show_bstr(const char *);

 

int main(void)

{

    char bin_str[8 * sizeof(int) + 1];

    int number;

 

    puts("Enter integers and see them in binary.");

    puts("Non-numeric input terminates program.");

    while (scanf("%d", &number) == 1)

    {

        itobs(number,bin_str);

        printf("%d is ", number);

        show_bstr(bin_str);

        putchar('/n');

    }

    puts("Bye!");

   

    return 0;

}

 

char * itobs(int n, char * ps)                      // 没太看懂怎么将数字转成32 位的

{

    int i;

    static int size = 8 * sizeof(int);

 

    for (i = size - 1; i >= 0; i--, n >>= 1)

        ps[i] = (01 & n) + '0';

    ps[size] = '/0';

   

    return ps;

}

 

// show binary string in blocks of 4

void show_bstr(const char * str)

{

    int i = 0;

      

    while (str[i]) 

    {

        putchar(str[i]);

        if(++i % 4 == 0 && str[i])

            putchar(' ');

    }

}

 

*/

 

//

//

//chapter 16

/* subst.c -- substitute in string */

/*

#include <stdio.h>

#define PSQR(x) printf("The square of %d  is %d./n",x,((x)*(x)))

 

int main(void)

{

    int y = 5;

 

    PSQR(y);

    PSQR(2 + 4);

   

    return 0;

}*/

//

 

/* subst.c -- substitute in string */

/*

#include <stdio.h>

#define PSQR(x) printf("The square of " #x " is %d./n",((x)*(x)))

 

int main(void)

{

    int y = 5;

 

    PSQR(y);

    PSQR(2 + 4);

   

    return 0;

}

*/

//

//varargs.c -- use variable number of arguments  使用可变个数的参数

/*

#include <stdio.h>

#include <stdarg.h>

double sum(int, ...);

 

int main(void)

{

    double s,t;

 

    s = sum(3, 1.1, 2.5, 13.3);

    t = sum(6, 1.1, 2.1, 13.1, 4.1, 5.1, 6.1);

    printf("return value for "

           "sum(3, 1.1, 2.5, 13.3):                 %g/n", s);

    printf("return value for "

           "sum(6, 1.1, 2.1, 13.1, 4.1, 5.1, 6.1): %g/n", t);

 

    return 0;

}

 

double sum(int lim,...)

{

    va_list ap;                   // declare object to hold arguments

    double tot = 0;

     int i;

 

    va_start(ap, lim);            // initialize ap to argument list

    for (i = 0; i < lim; i++)

       tot += va_arg(ap, double); // access each item in argument list

    va_end(ap);                   // clean up

 

    return tot;

}

*/

//

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值