getchar() and scanf() skipped in C [duplicate]

人盡茶涼 提交于 2019-12-13 19:50:17

问题


I'm currently writing a program that will copy or append one file's text into another. My problem comes up when the user is prompted whether they want to overwrite or append the file, scanf() and getchar() are both skipped. I have tried using numerous combinations of getchar()'s and scanf()'s along with fflush(stdin) and ensuring that all the files I had opened are close, but I still cannot input a selection.

The specific section of code containing the first prompt is here.

`/****************PROMPT FOR OVERWRITE****************/
printf("Would you like to overwrite the Destination File?\n");
printf("1=NO,2=YES=");
scanf("%d", &overwriteAnswer);
    if(overwriteAnswer == 2)
    {
`

This scanf() or, when I used getChar(), is just skipped and is usually filled with a different negative number every time the code is executed.

Full code follows

    if((infile = open(argv[1], O_RDONLY)) == 0)
    {
        /****************INPUT FILE OPENED****************/
        printf("%s open\n",argv[1]);
        if ((outfile = access(argv[1], F_OK)) == 0 )
        {
            /****************PROMPT FOR OVERWRITE****************/
            printf("Would you like to overwrite the Destination File?\n");
            printf("1=NO,2=YES=");
            scanf("%d", &overwriteAnswer);
            if(overwriteAnswer == 2)
            {
                printf("Overwriting Destination File\n");
            }

Any help or advice is greatly appreciated.


回答1:


I do not understand why you do not use fflush like that:

                printf("\nWould you like to append the Destination File?\n");
                printf("1=NO,2=YES=");
                fflush(stdin);
                scanf("%d", &appendAnswer);

EDIT:

if fflush(stdin) does not work, try to enforce scanf to read numbers in the following way:

    // additional variables
    char ch; // just a char to read from stream
    int wasNumber; // flag of successful scanf execution
    do{
        wasNumber = 0;
        // ask for input
        printf("\nWould you like to append the Destination File?\n");
        printf("1=NO, 2=YES : ");
        // read mumber
        wasNumber = scanf("%d", &appendAnswer);
        // clean the input bufer if it has not number
        if( wasNumber == 0 )
        {
            while( getchar() != '\n' ); // read till the end of line
        }
    }while(wasNumber != 1 || appendAnswer < 1 || appendAnswer > 2);


来源:https://stackoverflow.com/questions/28308319/getchar-and-scanf-skipped-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!