前記:最近在看《c和指針》-中文版,在這裏留個記號也好監督一下自己。文中列寫的代碼均以經過調試運行。
以下是第一章的例程 1-1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_COLS 20
#define MAX_INPUT 1000
int read_column_numbers(int column[],int max);
void rearrange(char *output, char const *input, \
int n_columns, int const columns[]);
int main(void)
{
int n_columns;
int columns[MAX_COLS];
char input[MAX_INPUT];
char output[MAX_INPUT];
/*read the mark number*/
n_columns = read_column_numbers(columns, MAX_COLS);//columns filled,columns SIZE
/*read, deal with, print*/
printf("Please input:\n");
while( gets( input) != NULL)//gets use way
{
printf("Original input : %s \n", input);
rearrange(output, input, n_columns, columns);//core code
printf("Rearrange line: %s\n",output);
}
return EXIT_SUCCESS;
}
/*read mark line*/
int read_column_numbers(int columns[], int max)
{
int num = 0;
int ch;
/*read mark number*/
while(num < max && scanf( "%d",&columns[num]) == 1 \
&& columns[num] >= 0) //until non-interger
num += 1;
/*confirm even mark number*/
if( num % 2 != 0)
{
puts("cuola! bu shi cheng dui de. ");
exit(EXIT_FAILURE);
}
/*pass last part of that line*/
while( (ch = getchar()) != EOF && ch != '\n')
;
return num;
}
/*deal with */
void rearrange(char *output, char const *input,\
int n_columns, int const columns[] )
{
int col;
int output_col;
int len;
len = strlen(input);
output_col = 0;
for( col = 0; col < n_columns; col += 2)
{
int nchars = columns[col + 1] - columns[col] + 1;
if(columns[col] >= len || \
output_col == MAX_INPUT - 1)
break;
if(output_col + nchars > MAX_INPUT - 1)
nchars = MAX_INPUT - output_col - 1;
strncpy( output + output_col, input + columns[col],\
nchars);// core code
output_col += nchars;
}
output[output_col] = '\0';
}
小結與思考:感覺這本書的寫作視角很特別,c語言的寫法也很獨特很地道,不僅考慮程序功能而寫考慮了代碼性能、結構等我以前所不屑內容。從這個例子上來時,出了功能實現之外,還涉及了越界判斷等,這是值得學習的。另外舉一個小例子,例程中在結束輸入列數對時(read_column_numbers函數中),程序思路是利用scanf()函數,使得一旦輸入非整數(當然包括字符)其返回值就不爲1,從而退出while()輸入循環。在驚歎於其使用的巧妙時,也在違心的說上一句“這我也會,只是沒想到”。仔細思考,你會發現對一些常見的函數理解還是不夠深入,從而導致不會寫出巧妙的代碼。抽象成一句話:精湛的技藝源於深入挖掘!