11.从键盘输入若干行字符(每行长度不等),输入后把它们存储到一磁盘文件中。再从该文件中读入这些数据,将其中小写字母转换成大写字母后在显示屏上输出。
#include<stdio.h>
int main()
{
int i,flag;
char str[80],c;
FILE *fp;
fp=fopen("text.dat","w");
flag=1;
while(flag==1)
{
printf("Input string:");
gets(str);
fprintf(fp,"%s",str);//把字符串str按%s的格式输出到fp指向的文件text中
printf("输入Y或y继续循环,输入其他字符结束循环:");
c=getchar();
getchar();//吸收回车产生的换行符
if((c=='Y')||(c=='y'))
flag=0;
printf("\n");
}
fclose(fp);
fp=fopen("text.dat","r");
printf("转换后的字符串为:");
while(fscanf(fp,"%s",str)!=EOF)//从fp指向的磁盘文件text中读取字符串送给字符串str
{
for(i=0;str[i]!='\0';i++)
{
if((str[i]>='a')&& (str[i]<='z'))//若字符串中有小写字母
str[i]=str[i]-32;//就把字符串中每个小写字母变成大写字母
}
printf("%s",str);
}
fclose(fp);
return 0;
}
在VS2019下,需将源文件的fopen和gets和fscanf做些修改:
#include<stdio.h>
int main()
{
int i, flag;
char str[80], c;
FILE* fp;
fopen_s(&fp, "text.dat", "w");
flag = 1;
while (flag == 1)
{
printf("Input string:");
gets_s(str, 80);
fprintf(fp, "%s", str);//把字符串str按%s的格式输出到fp指向的文件text中
printf("输入Y或y继续循环,输入其他字符结束循环:");
c = getchar();
getchar();//吸收回车产生的换行符
if ((c == 'Y') || (c == 'y'))
flag = 0;
printf("\n");
}
fclose(fp);
fopen_s(&fp, "text.dat", "r");
printf("转换后的字符串为:");
while (fscanf_s(fp, "%s", str, (unsigned int)sizeof(str)) != EOF)//从fp指向的磁盘文件text中读取字符串送给字符串str
{
for (i = 0; str[i] != '\0'; i++)
{
if ((str[i] >= 'a') && (str[i] <= 'z'))//若字符串中有小写字母
str[i] = str[i] - 32;//就把字符串中每个小写字母变成大写字母
}
printf("%s", str);
}
fclose(fp);
return 0;
}