这是我正在编写的程序的基本代码,用于练习使用 C 中的文件。我试图检测输出文件是否已经存在,如果确实存在,我想询问用户是否愿意覆盖它。这就是我首先使用 fopen(outfilename,"r"); 打开 outfilename 文件的原因;与 fopen(outfilename,"w"); 相反。
它检测文件不存在的情况,但是,如果存在,则执行 printf("输出文件已存在,覆盖 (y/n):");语句但完全忽略 scanf("%c",&yn);陈述!
如果文件不存在,则程序末尾的 printf 读取“yn=0”;如果文件存在,则读取“yn=”。有谁能够帮助我?
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <string.h>
int main(void) {
FILE *inf;
FILE *outf;
char filename[21],outfilename[21];
char yn='0';
printf("Please enter an input filename: ");
scanf("%s",&filename);
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
/* Open file for reading */
inf=fopen (filename,"r");
outf=fopen(outfilename,"r");
/*check that input file exists*/
if (inf!=NULL) {
/*check that the output file doesn't already exist*/
if (outf==NULL){
fclose(outf);
/*if it doesn't already exist create file by opening in "write" mode*/
outf=fopen(outfilename,"w");
} else {
/*If the file does exist, give the option to overwrite or not*/
printf("Output file already exists, overwrite (y/n):");
scanf("%c",&yn);
}
}
printf("\n yn=%c \n",yn);
return 0;
}
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
当您输入第二个字符串并按 ENTER 键时,一个字符串和一个字符将被放置在输入缓冲区中,它们是:输入的字符串和换行符。该字符串被scanf
但换行符仍保留在输入缓冲区中。
更远,
scanf("%c",&yn);
你的下一个scanf
读取字符只是读取/使用换行符,因此从不等待用户输入。
解决方案是使用以下方法消耗额外的换行符:
scanf(" %c", &yn);
^^^ <------------Note the space
或者通过使用getchar()
您可能想查看我的回答here https://stackoverflow.com/a/7826875/452307有关问题的详细逐步解释。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)