我怎样才能编写一个将文件中单词的第一个字符大写的 C 程序?
How can I do a C program that capitalizes the first characters of the words in the file?
#include <stdio.h>
int main()
{
FILE *fp;
int i;
int pos;
fp=fopen("test.txt","r+");
fseek(fp,0,SEEK_END);
pos=ftell(fp);
char ch[pos-1];
fseek(fp,0,SEEK_SET);
ch[0]=ch[0]-32;
i=0;
while(ch[i]=fgetc(fp)!=EOF){
if(ch[i]!=' '){
fseek(fp,1,SEEK_CUR);
i++;
}
else{
fseek(fp,1,SEEK_CUR);
i++;
ch[i]=fgetc(fp);
ch[i]=ch[i]-32;
fprintf(fp,"%c",ch[i]);
}
}
fclose(fp);
}
我想制作一个 C 程序,将文件中单词的第一个字符大写。但是当我 运行 这段代码 .txt 文件出错时。
fgetc() 的用法是否错误?
这个问题我的错在哪里? fscanf 是否移动光标?
在 while 循环的条件下,您有
ch[i] = fgetc(fp) != EOF
因为 != 的优先级高于 =,这等同于
ch[i] = (fgetc(fp) != EOF)
它不计算字符,而是比较中的 0 或非零值。
在我看来,更好的方法是读入整个字符串,修改它,然后以写入模式再次打开文件并写回,如果你要为无论如何内容。
#include <stdio.h>
int main()
{
FILE *fp;
int i;
int pos;
fp=fopen("test.txt","r+");
fseek(fp,0,SEEK_END);
pos=ftell(fp);
char ch[pos-1];
fseek(fp,0,SEEK_SET);
ch[0]=ch[0]-32;
i=0;
while(ch[i]=fgetc(fp)!=EOF){
if(ch[i]!=' '){
fseek(fp,1,SEEK_CUR);
i++;
}
else{
fseek(fp,1,SEEK_CUR);
i++;
ch[i]=fgetc(fp);
ch[i]=ch[i]-32;
fprintf(fp,"%c",ch[i]);
}
}
fclose(fp);
}
我想制作一个 C 程序,将文件中单词的第一个字符大写。但是当我 运行 这段代码 .txt 文件出错时。 fgetc() 的用法是否错误? 这个问题我的错在哪里? fscanf 是否移动光标?
在 while 循环的条件下,您有
ch[i] = fgetc(fp) != EOF
因为 != 的优先级高于 =,这等同于
ch[i] = (fgetc(fp) != EOF)
它不计算字符,而是比较中的 0 或非零值。
在我看来,更好的方法是读入整个字符串,修改它,然后以写入模式再次打开文件并写回,如果你要为无论如何内容。