18_11_29.c

C和指针1.1

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_COLS 20		//所能处理的最大列号
#define MAX_INPUT 1000	//每个输入行的最大行数

int read_column_numbers ( int columns[], int max );
void rearrange ( char* output, const char* input, int n_columns, const int columns[] );

int main ()
{
	int n_columns = 0;				//进行处理的列标号
	int columns[MAX_COLS] = {0};	//需要处理的列数
	char input[MAX_INPUT] = {0};	//容纳输入行
	char output[MAX_INPUT] = {0};	//容纳输出行
	//读取该串列标号
	n_columns = read_column_numbers ( columns , MAX_COLS );
	//读取,处理,打印剩余的输入行
	while( gets( input ) != NULL)
	{
		printf("输入原型:%s\n", input);
		rearrange (output, input, n_columns, columns);
		printf("重排结果:%s\n", output);
	}
	return 0;
}

int read_column_numbers ( int columns[], int max )
{
	int num = 0;
	int ch = 0;
	//取得列标号,如所读取数小于零则停止
	while( num < max && scanf("%d",&columns[num]) == 1 && columns[num] >= 0 )
	{
		num++;
	}
	//确认所读取列标号是成对的
	if( num % 2 != 0 )
	{
		puts("最后一列数字不是成对的。");
		exit(1);  //非正常运行导致退出程序
	}
	//丢弃该行中包含最后一个数字的那部分
	while( (ch = getchar()) != EOF && ch != '\n' )  //EOF文件结尾标志
	{
		;
	}
	return num;
}

void rearrange ( char* output, const char* input, int n_columns, const int columns[] )
{
	int col = 0;			//columns数组的下标
	int output_col = 0;		//输出列计数器
	int len = 0;			//输出行的长度
	len = strlen( input );
	//处理每对列标号
	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 );
		output += nchars;
	}
	output[output_col] = '\0';
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值