C - 是/否提示执行多次

时间:2013-03-01 17:34:03

标签: c prompt

我正在处理一个程序的一部分,该程序处理覆盖目录中的文件。覆盖文件很容易......但显然会询问用户是否要覆盖文件的提示不是。例如:如果我想覆盖两个文件(fileOne.txt,fileTwo.txt),我需要提示用户两次(每个文件一次)。在我当前的提示下,如果我提示用户覆盖fileOne.txt,则会覆盖fileOne.txt和fileTwo.txt。如果要覆盖的文件超过两个,则只会覆盖两个连续的文件。我认为它与点击“回车”有关,但我不知道......

if(((int)getHeader.deleted - 48) == 0) {
        if(access(getHeader.file_name, F_OK) != -1) { /* File exists in directory, check for overwrite */
            printf("%s already exists. Would you like to overwrite it? (y/n)\n", getHeader.file_name);
            scanf("%c", buffer);
            while(!validResponse) {
                if(buffer[0] == 'y' || buffer[0] == 'Y') {
                    validResponse = 1;
                    printf("DO SOMETHING - Files will be overwritten\n");
                } else if(buffer[0] == 'n' || buffer[0] == 'N') {
                    validResponse = 1;
                    printf("DO SOMETHING - File will be skipped\n");
                } else {
                    printf("Invalid response... Would you like to overwrite %s? (y/n)\n", getHeader.file_name);
                    scanf("%c", buffer);
                } /* End if else */
            } /* End while */
        } /* End if */
    } /* End if */ 

1 个答案:

答案 0 :(得分:3)

当您阅读单个字符时,在stdin中留下换行符,您需要使用该字符:

scanf("%c", buffer);
getchar();  // consume the leftover '\n'

会这样做,或只是在线上:

scanf(" %c", buffer); // the space will tell it to skip any "white space" characters


只有你在这里的代码片段,如果在第一个提示输入了无效字符,它似乎会被else的scanf跳过(实际上它正在读取第一个剩余的'\n')并且它会再次循环以获得输入。

如果没有看到剩下的代码,大概就是你将这一切都放在一个循环中,这就是为什么它在2s中跳过文件的原因。 ('Y',然后'\n'