从一个文件中读取一篇英文文章,请将文章中所有单词首字母大写并存入另一个文件中。“单词”是指一串连续的字母。
函数接口定义:
void CapitalizeTheFirstLetter(FILE *in, FILE *out);
说明:参数 in 和 out 为指示两个文件的指针。函数从 in 所指文件中的读出数据,将结果写入 out 所指的文件中。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void CapitalizeTheFirstLetter(FILE *in, FILE *out);
int main()
{
FILE *in, *out;
in = fopen("in.txt", "r");
out = fopen("out.txt", "w");
if (in && out)
{
CapitalizeTheFirstLetter(in, out);
}
else
{
puts("文件无法打开!");
}
if (in)
{
fclose(in);
}
if (out)
{
fclose(out);
puts("文件保存成功!");
}
return 0;
}
/* 请在这里填写答案 */
输入样例:
Spring Morning
translated by Xu Yuanchong
This spring morning in bed I am lying,
not awake till birds are crying.
After one night of wind and showers,
how many are the fallen flowers.
输出样例:
程序运行结束后,打开“out.txt”文件,查看文件内容。
Spring Morning
Translated By Xu Yuanchong
This Spring Morning In Bed I Am Lying,
Not Awake Till Birds Are Crying.
After One Night Of Wind And Showers,
How Many Are The Fallen Flowers.
代码:
void CapitalizeTheFirstLetter(FILE* in, FILE* out) {
char ch;
int flag = 0;
while ((ch = fgetc(in)) != EOF) {
if (flag == 0 && (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
if (islower(ch))
ch = toupper(ch);
flag = 1;
}
else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
flag = 1;
else
flag = 0;
fputc(ch, out);
}
}
注意:
1.if是判断是否为首字母,而else if则是判断是否为字母,如果是首字母,则首字母大写。
else则是判断空格,因为fgetc会读取空格
2.如果flag是1则不会使字母大写,如果是遇到空格,则下一个是首字母,会使其大写