【问题标题】:getchar() and scanf() skipped in C [duplicate]getchar() 和 scanf() 在 C 中跳过 [重复]
【发布时间】:2015-02-03 20:40:45
【问题描述】:

我目前正在编写一个程序,它将一个文件的文本复制或附加到另一个文件中。当提示用户是否要覆盖或附加文件时,我的问题出现了, scanf() 和 getchar() 都被跳过了。我尝试过使用 getchar() 和 scanf() 的多种组合以及 fflush(stdin) 并确保我打开的所有文件都已关闭,但我仍然无法输入选择。

包含第一个提示的具体代码部分在这里。

`/****************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() 时,它只是被跳过,并且每次执行代码时通常填充不同的负数。

完整代码如下

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

非常感谢任何帮助或建议。

【问题讨论】:

  • 我实际上已经阅读了所有这些并尝试实施他们所说的话,不幸的是它根本没有帮助我。
  • 不幸的是,它仍然跳过了两个 scanf() 的完成。
  • 不。执行是 ./a.out [sourcefile] [destinationfile].
  • 这产生了一个错误,指出在提示覆盖或附加之前无法打开该文件。有点意思,因为它现在似乎不能正常工作。
  • 我要试一试。

标签: c input copy scanf getchar


【解决方案1】:

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

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

编辑:

如果fflush(stdin)不起作用,请尝试强制scanf按以下方式读取数字:

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

【讨论】:

  • 我有,它没有为我解决任何问题。刚刚再次尝试仔细检查。
  • 另外,代码中只有两个scanf(),第一个也被跳过了。
  • 您是否尝试过调试器以确保该程序可以到达 scanf ?
  • 我已经用调试器完成了 gcc,但没有任何显示。覆盖和追加的打印语句都打印完整。如果我打印出overwriteAnswer的值,第一个scanf(),每次都是不同的负数。我很肯定它正在实现。
  • 不,这就是问题所在。它不会在任何一个 scanf() 处停止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 2013-01-07
  • 1970-01-01
相关资源
最近更新 更多