C和指针_第一章编程练习

C和指针第一章1.8编程练习


1.第一题

#include<stdio.h>

int main()
{
	printf("Hello World!\n");
}

2.第二题

#include<stdio.h>
#include<stdlib.h>

int main()
{
	int c;
	bool at_begining;
	int line;

	at_begining = true;
	line = 0;
	
	while ((c = getchar()) != EOF)
	{
		if (at_begining == true)
		{
			at_begining = false;
			line += 1;
			printf("%d ", line);
		}
		putchar(c);
		if (c == '\n')
		{
			printf("\n");
			at_begining = true;
		}
	}
	
	return 0;
}

3.第三题

#include <stdio.h>
int main()
{
	signed char checksum = -1;
	int ch;

	while ((ch = getchar()) != EOF)
	{
		putchar(ch);
		checksum += ch;
		if (ch == '\n')
		{
			printf("%d\n", checksum);
			checksum = -1;
		}
	}

	return 0;
}

4.第四题

#include <stdio.h>
#include<string.h>
int main()
{
	int max;
	int temp;
	char str[1000];
	char tmp[1000];
	temp = max = 0;

	while (fgets(tmp, 1000, stdin))
	{
		temp = strlen(tmp);
		if (max < temp)
		{
			max = temp;
			strcpy(str, tmp);
		}
	}

	printf("最长输入行:%s\n",str);
	printf("长度为: %d\n",max);
}

5.第五题

if (columns[col] >= len||output_col == MAX_INPUT - 1)
		braek;

将上述代码修改为以下

if (columns[col] >= len)
	continue;
if (output_col == MAX_INPUT - 1)
	break;

6.第六题

1.删除注释的内容

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 += 1;
/*
	确认是否是偶数个
	if (num % 2 != 0)
	{
		puts("Last column number is not paired");
		exit(EXIT_FAILURE);
	}
*/

	//丢弃该行中包含最后一个数字的那部分内容
	while ((ch = getchar()) != EOF && ch != '\n')
		;
	return num;
}

2.添加对奇数列处理的代码

void rearrange(char* output, char const* input, int n_columns, int columns[])
{
	int col;         //colummns数组的下标
	int output_col;	//输出列计数器
	int len;       //输入行的长度

	len = strlen(input);
	output_col = 0;
	
	//对奇数个列标进行处理
	if (n_columns % 2 != 0)
	{
		columns[n_columns] = len - 1;
	}

	/*
	* 处理每对列标号
	*/
	for (col = 0; col < n_columns; col += 2)
	{
		int nchars = columns[col + 1] - columns[col] + 1;

		//输入行结束或输出行数组已满,结束任务
		if (columns[col] >= len)
				continue;
		if(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;
		output[output_col] = '\0';
	}
}

总结

以上为C和指针第一章的编程练习。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值