C Primier Plus(第六版)第8章 编程练习 VS2019测试

第1题

/*编程练习8.1 设计一个程序,统计在读到文件结尾之前读取的字符数*/
#include<stdio.h>
#include<stdlib.h>	//使用exit()

int main(void)
{
   
	char ch;
	FILE* fp;
	errno_t err;	//如果成功,返回值为零;如果失败,则为错误代码。
	long n = 0;

	if ((err = fopen_s(&fp,"D:\\Project\\practice8_1\\Shakespeare.txt", "r")) != 0) {
   
		printf("Cannot open file, press any key to exit!");
		/*fopen_s(&fp, "newfile.txt", "rw, ccs=**_encoding_**"); "r"打开以便读取。
		如果文件不存在或找不到,调用将 fopen_s 失败。*/
		exit(1);
	}

	//每次读取一个字节,直到读取完毕
	while ((ch = fgetc(fp)) != EOF) {
   
		putchar(ch);
		n++;	//读取字节成功,计数
	}
	putchar('\n');  //输出换行符
	fclose(fp);
	printf("\nThe file has %d characters.\n", n);
	return 0;
}

第2题

/*编程练习8.2 编写一个程序,在遇到EOF之前,把输入作为字符流读取。程序要打印每个输入
的字符及其相应的ASCII十进制值……(略)除遇到换行符打印心得一行之外,每行打印10对值*/
#include<stdio.h>

int main(void)
{
   
	char ch;
	int i=0;

	printf("Please enter some text for analysis.\n");
	while ((ch = getchar()) != EOF) {
   		
			if (ch == '\n') {
   
				printf("\\n-%3d", (int)ch);
				putchar('\n');
				i = 0;
			}
			else if (ch == '\t') {
   
				printf("\\t-%3d  ", (int)ch);
				i++;
			}
			else {
   
				printf("%c-%3d  ", ch, (int)ch);
				i++;
			}
		if (i == 10) {
   
			putchar('\n');
			i = 0;
		}
	}
	printf("\nDone!");

	return 0;
}

第3题(方法1,ASCII值连续)

/*编程练习8.3 编写一个程序,在遇到EOF前,把输入作为字符流读取。程序要报告输入中
的大写小写字母个数。*/
/*方法1:假设字母大小写数值是连续的(可以转换为ASCII值)*/
#include<stdio.h>

int main(void)
{
   
	int num_upper = 0, num_lower = 0;	//定义大小写字母个数
	char ch;

	printf("Please enter some text for analysis.\n");
	while ((ch = getchar()) != EOF)
	{
   
		if (ch >= 'a' && ch <= 'z')
			num_lower++;
		if (ch >= 'A' && ch <= 'Z'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值