c和c指针
2014-04-16 20:59
281 查看
c指针
/* * 这个程序从标准输入中读取输入行并在标准输出中打印这些输入行, * 每个输入行的后面一行是该内容的一部分, * 输入的第一行是一串列标号,串的最后以一个负数结尾。 * 这些列表号成对出现,说明需要打印的输入行的范围。 * 列如,0 3 10 12 -1 表示0列到第3列,第10列到第12列的内容被打印。 */ #include "stdio.h" #include "stdlib.h" #include "string.h" #define MAX_INPUT 1000 /*所能处理的最大列号*/ #define MAX_COLS 20 /*每个输入行的最大长度*/ int read_column_numbers(int columns[], int max); void rearrange( char *output, char const *input, int n_columns, int const colums[]); int main( void ) { int n_columns; /*进行处理的列标号*/ int columns[ MAX_COLS ]; /*需要处理的列数*/ char input[MAX_INPUT]; /*容纳输入行的数组*/ char output[ MAX_INPUT]; /*容纳输出行的数组*/ /*读取该串列标号*/ n_columns = read_column_numbers( columns, MAX_COLS ); /*读取、处理和打印剩余的输入行*/ while ( gets( input ) != NULL ){ printf (" Original input: %s\n", input ); rearrange( output, input, n_columns, columns); printf ("Rearranged line: %s\n", output ); } return EXIT_SUCCESS; } /*读取列标号,如果超出规定范围则不予理会。*/ int read_column_nubber( int columns[], int max) { int num = 0; int ch; /*取得列标号,如果所读取的数小于0则停止*/ while ( num < max && scanf ("%d", &columns[num] ) == 1 && columns[num] >= 0) num += 1; /*确认以读取的标号为偶数个,因为它们是以对的形式出现的*/ if ( num %2 != 0){ puts( "Last column number is not paired."); exit ( EXIT_FAILURE); } /*丢弃该行中包含最后一个数字的那部分内容。*/ while ( ( ch = getchar()) != EOF && ch != '\n' ) ; return num; } /*处理输入行,将指定的字符连接在一起,输出以NULL结尾*/ void rearrange( char *output, char const *input, int n_columns, int const columns[]) { int col; /*colums数组的下标*/ 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 ] == 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; } output [ output_col ] = '\0'; }
相关文章推荐
- 第十六周 项目二 用指针玩转字符串
- 指针数组与数组指针
- C/C++学习笔记:指向类成员变量的指针
- 指针
- c指针、数组(计算大小)
- free 一个指针时【 retval = HeapFree(_crtheap, 0, pBlock);】报错的原因
- 条款13-15(资源管理,其实就是讲的智能指针)
- 智能指针单例
- C++学习笔记(八):函数重载、函数指针和函数对象
- 用汇编的眼光看C++(之指针1)
- 普通方法指针,对象方法指针和对象方法指针的指针.
- 结构体、共用体、指针
- 指针拷贝小例子
- 初试指针---原来指针可以这样用啊!
- C++ 常量指针和指针常量
- 第8周项目3-指向学生类的指针
- list的addAll出现空指针问题
- 解析指针数组,数组指针,函数指针,函数指针数组,指向函数指针数组的指针
- 二级指针拷贝
- 指针数组&&数组指针||指针函数&&函数指针