在C中跳过了getchar()和scanf()

我目前正在编写一个程序,将一个文件的文本复制或附加到另一个文件中。 当提示用户是否要覆盖或追加文件时,我的问题就出现了,我们都跳过了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"); } 

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

我不明白你为什么不这样使用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);