c - if else 语句双重打印 C

标签 c if-statement do-while

我正在编写一个向 C 文件添加行号的程序。我将文件名作为命令行参数获取,但我希望用户在运行程序时忘记输入它们时有机会输入它们。我询问用户是否要输入文件名,然后他们回答“y”或“n”。如果输入了无效字符,他们将被给予五次尝试来正确回答,但五次尝试后,程序会打印一条错误消息并终止。如果用户输入无效字符,我会打印“[y/n]?”到屏幕上提示用户输入这些字母。如果输入了无效字符,它会执行两次循环并将它们并排打印出来。为什么会出现这种情况?

编译器.c文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lineNumAdderHeader.h"
#include "miscellaneousHeader.h"
#include "errorCheckedFunctionsHeader.h"

int main(int argc, char *argv[]){
int i = 1;
char ch;
int answerTries = 0;
char *seperatedFilenames[argc - 1];

if (argc < 2){
    fprintf(stderr, "No files were entered for compiling.\n");

    answer: do{
        if (answerTries == 0)
            printf("Would you like to enter files for compiling [y/n]? ");
        else if (!(answerTries < 5))
             fatal("in main(). An invalid character was entered too many times.");
        else
            printf("[y/n]? ");

        ch = getchar();

        if (ch == 'n' || ch == 'N')
            exit(0);

        answerTries++;
    } while (ch != 'y' && ch != 'Y');
}
else{
    while (i < argc){
        seperatedFilenames[i - 1] = argv[i];
        i++;
    }
}

i = 0;
while (i < (argc - 1)){
    lineNumAdder(seperatedFilenames[i]);
    i++;
}
}

致命功能:

/*Displays a fatal error*/
void fatal(char *errorMessage){
/*Holds the errorMessage*/
char completedErrorMessage[strlen(errorMessage) + 17];

/*Copies the error message into completedErrorMessage*/
strcpy(completedErrorMessage, "[!!] Fatal Error ");
strcat(completedErrorMessage, errorMessage);

/*Prints the error message to the screen*/
fprintf(stderr, "%s\n", completedErrorMessage);

/*Exit the program in failure*/
exit(-1);
}

最佳答案

您的 getchar() 调用从标准输入返回一个字符。当用户输入答案时,他按下回车/返回键,该键会转换为换行符,该换行符是该行的一部分,然后发送到标准输入。

您可能应该做的是仅检查 getchar 返回的第一个字符,然后在循环中读取并丢弃所有字符,直到获得新行字符(\n)。只有这样,您才能再次提问。

您应该使用此循环,因为您的用户可能会同时输入多个字符。例如,他可以输入“yes”,这将算作 4 个字符。

关于c - if else 语句双重打印 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887096/

相关文章:

java - C:以编程方式查找 JVM 库文件位置

c++ - 为给定窗口遍历 MSAA 树的代码(Microsoft Active Accessibility)?在 C/C++ 中

linux - 从脚本中的文本文件中提取用户名

c - 错误 :Socket Select() function always return zero. 。?

c - UVa-401 :Palindromes, 超出输出限制

带有 if 语句的 Python oneliner

javascript - 对具有多个条件的对象进行排序

c - 再玩一次函数c

c++ - 如何解决此问题以编写使用 while 循环计算前 n 个斐波那契数的程序

java - do-while 循环问题