且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

程序不等待与scanf的用户输入("%C",&安培; YN);

更新时间:2023-02-15 20:14:23

 的printf(请输入一个输出文件名:);
scanf函数(%S,&安培; outfilename);

当你进入第二个字符串,然后按Enter键,一个字符串的字符被放置在输入缓冲区中,他们分别是:输入的字符串和换行符character.The字符串获取由 scanf的但换行保持在输入缓冲器

另外,

  scanf函数(%C,&安培; YN);

您接下来的 scanf函数读取字符只是读取/消耗换行符,因此从不等待用户输入。

解决方案是消耗使用额外的换行符:

  scanf函数(%C,&安培; YN);
      ^^^< ------------注意空间

或使用的getchar()

您可能想看看我的答案 这里 作为一步解释详细的一步的问题。

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");.

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!

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("\n yn=%c \n",yn);
    return 0;
}

printf("Please enter an output filename: ");    
scanf("%s",&outfilename);

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.

Further,

scanf("%c",&yn);

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

Or by using getchar()

You may want to check out my answer here for a detailed step by step explanation of the problem.