由於以後公司開發要用到C和Oracle, 又把C和指針看了一篇
然後就寫點博客 做點練習(主要是標三星題目)
#include <stdio.h>
#include <stdlib.h>#include <string.h>
#define MAX_COLS 20 //表示最大的列號
#define MAX_INPUT 200 //表示每個輸入行的最大長度
bool check_numbers(int columns[]) //課後第五題 添加的函數
{
int i = 0;
int len = sizeof(columns) / sizeof(columns[0]);
bool flag = false;
while(i < len-1)
{
if(columns[i] > columns[i+1]) //保正前一個比後一個小
{
flag = true;
break;
}
}
return flag;
}
int read_column_numbers(int column[], int max)
{
int num = 0;
int ch; //表示作爲中間賦值數據
//數據輸入 並且進行判斷
while( (num<max) && scanf("%d", &column[num])==1 && column[num]>=0 )
num += 1;
//保證是偶數個
if(num % 2 != 0)
{
puts("It must be divided by 2\n");
exit(EXIT_FAILURE);
}
//丟棄最後一部分
while((ch = getchar()) != EOF && ch != '\n') ;
if( !check_numbers(column) )
return 0;
return num;
}
void rearrange(char *output, const char* input, int n_cols, const int columns[])
{
int col; //數組的下標
int output_col = 0; //輸出列計數器
int len = strlen(input); //輸入行的長度
for(col=0; col<n_cols; 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); //進行數據的拷貝
output_col += nchars; //下次計算在使用 保證數據的範圍可控
}
}
int main()
{
int n_columns; //進行處理的列標號
int columns[MAX_COLS]; //數據列數
char input[MAX_INPUT] = {'0'};
char output[MAX_INPUT] ={'0'};
n_columns = read_column_numbers(columns, MAX_COLS);
if(n_columns == 0)
{
printf("the input data is error\n");
return 0;
}
while( gets(input) != NULL )
{
printf("First input: %s\n", input);
rearrange(output, input, n_columns, columns);
printf("Last output: %s\n", output);
}
return 0;
}
//課後第六題也比較簡單啊 可以將num值減一 然後讀取的還是偶數個