选择列范围并输出

发布时间 2024-01-11 17:11:11作者: SRnewcity

62 行对还是64行对
1
#include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define MAX_COLS 20 5 #define MAX_INPUT 1000 6 7 int read_column_numbers( int columns[], int max ); 8 void rearrange( char *output, char const *input, 9 int n_columns, int const columns[] ); 10 11 int main( void ) 12 { 13 int n_columns; 14 int columns[MAX_COLS]; 15 char input[MAX_INPUT]; 16 char output[MAX_INPUT]; 17 18 n_columns = read_column_numbers( columns, MAX_COLS ); 19 while( gets(input) != NULL){ 20 printf("Original input : %s\n", input); 21 rearrange( output, input, n_columns, columns ); 22 printf("Rearranged line: %s\n", output); 23 } 24 25 return EXIT_SUCCESS; 26 } 27 28 int read_column_numbers( int columns[], int max) 29 { 30 int num = 0; 31 int ch; 32 33 while( num < max && scanf( "%d", &columns[num]) == 1 && columns[num] >= 0) 34 num += 1; 35 if( num % 2 != 0){ 36 puts( "Last column number is not paired." ); 37 exit( EXIT_FAILURE ); 38 } 39 40 while ( (ch = getchar()) != EOF && ch != '\n' ) 41 ; 42 43 return num; 44 } 45 46 void rearrange( char *output, char const *input, int n_columns, int const columns[] ) 47 { 48 int col; 49 int output_col; 50 int len; 51 52 len = strlen( input ); 53 output_col = 0; 54 55 for (col = 0; col < n_columns; col += 2) 56 { 57 int nchars = columns[col + 1] - columns[col] + 1; 58 59 if (columns[col] >= len || output_col == MAX_INPUT - 1) 60 break; 61 if (output_col + nchars > MAX_INPUT - 1) 62 nchars = MAX_INPUT - output_col; 63 // Or this 64 // nchars = MAX_INPUT - output_col - 1; 65 strncpy( output + output_col, input + columns[col], nchars ); 66 output_col += nchars; 67 } 68 output[output_col] = '\0'; 69 }