的getchar()和scanf()跳过用C [英] getchar() and scanf() skipped in C

查看:192
本文介绍了的getchar()和scanf()跳过用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在写一个程序,复制或一个文件的文本追加到另一个。当用户被提示是否要覆盖或添加文件和scanf()和getchar函数()都跳过我的问题出现了。我一直在使用的getchar的多种组合()的和scanf()的使用fflush(标准输入)一起,并确保所有我打开的文件都接近试过,但我还是不能输入选择。

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.

code包含第一个提示的特定部分是在这里。

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)
    {
`

这scanf()的,或者,当我用的getchar(),只是跳过,每次执行code时间通常充满了不同的负数。

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.

全部code如下

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

任何帮助或建议是大大AP preciated。

Any help or advice is greatly appreciated.

推荐答案

我不明白你为什么不使用fflush这样的:

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

编辑:

如果 fflush(标准输入)不起作用,尝试执行 scanf函数阅读下列方式的数字:

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

这篇关于的getchar()和scanf()跳过用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆