我正在尝试将文件中的大小写转换为另一个文件。我要转换的文件有空格和几行。转换后的表格没有空格且没有换行符。有谁知道我该如何更改代码,使其包含原始文件中的空格和换行符?
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main(void)
{
FILE *fp1, *fp2;
fp1 = fopen("exercise2.txt", "r");
fp2 = fopen("exercise2_converted.txt", "w");
int singleline;
if (fp1 == NULL)
{
printf("Error opening fp1!\n");
return 0;
}
if (fp2 == NULL)
{
printf("Error opening fp2!\n");
fclose(fp1);
return 0;
}
do
{
singleline = fgetc(fp1);
if (islower(singleline))
{
singleline = toupper(singleline);
fputc(singleline, fp2);
}
else if (isupper(singleline))
{
singleline = tolower(singleline);
fputc(singleline, fp2);
}
} while (singleline != EOF);
fclose(fp1);
fclose(fp2);
return 0;
}
答案 0 :(得分:2)
总体初学者的解决方案:
...
do
{
singleline = fgetc(fp1);
if (singleline == EOF)
break; // end of file => game over quit loop immediately
// convert char if neessary
if (islower(singleline))
{
singleline = toupper(singleline);
}
else if (isupper(singleline))
{
singleline = tolower(singleline);
}
// output the char
fputc(singleline, fp2);
} while (1);
...
解决方案较短,但对于初学者来说更难阅读和理解。