程序不等待用户输入 scanf("%c",&yn); [英] Program doesn't wait for user input with scanf("%c",&yn);
问题描述
这是我正在编写的程序的基本代码,用于练习使用 C 中的文件.我试图检测输出文件是否已经存在,如果确实存在,我想询问用户是否想覆盖它或不.这就是我首先用 fopen(outfilename,"r"); 打开 outfilename 文件的原因;与 fopen(outfilename,"w"); 相反.
This is the basic code to a program I am writing to practise using files in C. I am trying to detect whether the output file already exists and if it does exist I want to ask the user if they would like to overwrite it or not. This is the reason that I have first opened the outfilename file in with fopen(outfilename,"r"); as opposed to fopen(outfilename,"w");.
它检测文件不存在的情况,但是,如果它确实存在,则执行 printf("Output file already exists, overwrite (y/n):");语句但完全忽略了 scanf("%c",&yn);陈述!
It detects the case of the file not existing, however, if it does exist it executes the printf("Output file already exists, overwrite (y/n):"); statement but completely ignores the scanf("%c",&yn); statement!
如果文件不存在,程序末尾的 printf 读取yn=0",如果文件存在则读取yn=".有人可以帮我吗?
The printf at the end of the program reads "yn=0" if the file doesn't exist and just "yn=" if it does exist. Can anybody help me?
#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("
yn=%c
",yn);
return 0;
}
推荐答案
printf("Please enter an output filename: ");
scanf("%s",&outfilename);
当您输入第二个字符串并按 ENTER 键时,输入缓冲区中会放置一个字符串和一个字符,它们分别是:输入的字符串和换行符.该字符串被 scanf
但换行符保留在输入缓冲区中.
When you enter the second string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character.The string gets consumed by the scanf
but the newline remains in the input buffer.
进一步,
scanf("%c",&yn);
您下一个用于读取字符的 scanf
只是读取/消耗换行符,因此从不等待用户输入.
Your next scanf
for reading the character just reads/consumes the newline and hence never waits for user input.
解决方案是使用额外的换行符:
Solution is to consume the extra newline by using:
scanf(" %c", &yn);
^^^ <------------Note the space
或者通过使用 getchar()
您可能想在此处查看我的回答以获取详细的分步说明问题.
You may want to check out my answer here for a detailed step by step explanation of the problem.
这篇关于程序不等待用户输入 scanf("%c",&yn);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!