简体   繁体   English

程序不等待用户输入 scanf("%c",&yn);

[英]Program doesn't wait for user input with scanf("%c",&yn);

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.这是我正在编写的程序的基本代码,用于练习使用 C 中的文件。我试图检测输出文件是否已经存在,如果它确实存在,我想询问用户是否愿意覆盖它。 This is the reason that I have first opened the outfilename file in with fopen(outfilename,"r");这就是我首先使用 fopen(outfilename,"r"); 打开 outfilename 文件的原因。 as opposed to fopen(outfilename,"w");.而不是 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):");它检测文件不存在的情况,但是,如果确实存在,则执行 printf("Output file already exists, overwrite (y/n):"); statement but completely ignores the scanf("%c",&yn);声明但完全忽略 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.如果文件不存在,程序末尾的 printf 将读取“yn=0”,如果文件存在,则读取“yn=”。 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.当您输入第二个字符串并按 ENTER 键时,一个字符串和一个字符被放置在输入缓冲区中,它们是:输入的字符串和换行符。该字符串被scanf消耗,但换行符保留在输入中缓冲。

Further,更远,

scanf("%c",&yn);

Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input.您用于读取字符的下一个scanf只是读取/使用换行符,因此从不等待用户输入。

Solution is to consume the extra newline by using:解决方案是使用以下方法消耗额外的换行符:

scanf(" %c", &yn);
      ^^^   <------------Note the space

Or by using getchar()或者通过使用getchar()

You may want to check out my answer here for a detailed step by step explanation of the problem.您可能想在此处查看我的答案,以获取对该问题的详细分步说明。

Use利用

scanf("%20s",&filename);

and remember that stdin is line buffered and on Linux is following a tty discipline请记住, stdin是行缓冲的,并且在 Linux 上遵循tty规则

You could use GNU readline or ncurses if you want more detailed control.如果您想要更详细的控制,您可以使用GNU readlinencurses

The better way to handle this problem I found is explained here<\/a> .这里解释了<\/a>我发现的处理这个问题的更好方法。

It recomends to use an alternative way of handle input and is very well explained.它建议使用另一种处理输入的方式,并且解释得很好。

I use always this function to get user input.我总是使用这个函数来获取用户输入。


char * read_line (char * buf, size_t length) {
    /**** Copyright de home.datacomm.ch/t_wolf/tw/c/getting_input.html#skip
    Read at most 'length'-1 characters from the file 'f' into
    'buf' and zero-terminate this character sequence. If the
    line contains more characters, discard the rest.
    */
    char *p;
    if ((p = fgets (buf, length, stdin))) {
        size_t last = strlen (buf) - 1;
        if (buf[last] == '\n') {
            /**** Discard the trailing newline */
            buf[last] = '\0';
        } else {
            /**** There's no newline in the buffer, therefore there must be
            more characters on that line: discard them!
            */
            fscanf (stdin, "%*[^\n]");
            /**** And also discard the newline... */
            (void) fgetc (stdin);
        } /* end if */
    } /* end if */
    return p;
} /* end read_line */

scanf("%s", ...) leaves the \\n terminating the line in the input. scanf("%s", ...)在输入中留下 \\n 终止行。 It isn't causing a problem for the next one as scanf("%s", ...) starts by skipping whites.它不会导致下一个问题,因为 scanf("%s", ...) 从跳过白人开始。 scanf("%c", ...) doesn't and thus you read the \\n . scanf("%c", ...)没有,因此您阅读了\\n

BTW You'll probably meet other problems is you put spaces in your file name ( %s doesn't read them) and if you enter too long names (%s has no input length limitations).顺便说一句,您可能会遇到其他问题,即您在文件名中添加了空格( %s不会读取它们)以及输入的名称太长(%s 没有输入长度限制)。

One solution for the problem you complained (but not the other one) is to use scanf(" %c", ...) (see the space before %c ? scanf is tricky to use) which starts by skipping white spaces.您抱怨的问题的一种解决方案(但不是另一个)是使用scanf(" %c", ...) (请参阅%c之前的空格? scanf很难使用),它首先跳过空格。

scanf("%s",&filename);

also remove the &也删除 &

scanf.c:13: warning: format '%s' expects type 'char ', but argument 2 has type 'char ( )[20u]' scanf.c:13:警告:格式“%s”需要类型“char ”,但参数 2 的类型为“char ( )[20u]”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM