如何将文本文件字符转换为大写字母?

时间:2022-12-09 18:52:42

I am using C Programming Language. I want to convert characters in text file to uppercase letters and print text file contents on the screen after conversion.

我正在使用C编程语言。我想在转换后将文本文件中的字符转换为大写字母并在屏幕上打印文本文件内容。

Here is my code:

这是我的代码:

 #include <stdio.h>
 #include <string.h>

 int main()
 {
 FILE *fptr;
 char filename[30];
 char ch;

printf("Enter filename you want to make capital letters: \n");
scanf("%s",filename);

fptr = fopen(filename,"r");

ch = fgetc(fptr);
while(ch != EOF)
{
ch = toupper(ch);
printf("%c",ch);
ch = fgetc(fptr);
}

fclose(fptr);

return 0;
}

1 个解决方案

#1


You are well on your way! Here are some recommended adjustments:

你很顺利!以下是一些建议的调整:

First, char ch should be int ch. Take a look at the manual page for fgetch and you will find that it returns an int. This is actually pretty important, because the EOF returned will be out of range for a char but in range for an int.

首先,char ch应该是int ch。看一下fgetch的手册页,你会发现它返回一个int。这实际上非常重要,因为返回的EOF将超出char的范围,但是在int的范围内。

Next, you could simplify a bit. Why not:

接下来,您可以简化一下。为什么不:

while((ch = fgetc(ptr)) != EOF)
{
  printf("%c", (char)ch);
}

This moves your logical test and your read into a single line, eliminating the two lines that currently have the fgetch in them.

这会将您的逻辑测试和读取移动到一行,从而消除当前具有fgetch的两行。

Finally, you should #include<ctype.h> since that is the header file where int toupper(int) is defined.

最后,您应该#include ,因为这是定义int toupper(int)的头文件。

#1


You are well on your way! Here are some recommended adjustments:

你很顺利!以下是一些建议的调整:

First, char ch should be int ch. Take a look at the manual page for fgetch and you will find that it returns an int. This is actually pretty important, because the EOF returned will be out of range for a char but in range for an int.

首先,char ch应该是int ch。看一下fgetch的手册页,你会发现它返回一个int。这实际上非常重要,因为返回的EOF将超出char的范围,但是在int的范围内。

Next, you could simplify a bit. Why not:

接下来,您可以简化一下。为什么不:

while((ch = fgetc(ptr)) != EOF)
{
  printf("%c", (char)ch);
}

This moves your logical test and your read into a single line, eliminating the two lines that currently have the fgetch in them.

这会将您的逻辑测试和读取移动到一行,从而消除当前具有fgetch的两行。

Finally, you should #include<ctype.h> since that is the header file where int toupper(int) is defined.

最后,您应该#include ,因为这是定义int toupper(int)的头文件。