问题
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