第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'