2015-11-15 55 views
0

这是一个代码到输入文件中的数据到一个新的文件,如果输出文件已经存在,用户将有选择提供新地址或退出。 当我把goto readout放在开关里面时,开关就开始工作了,但是之后程序退出了,而没有输出文件地址。 这是截图: this is the screenshot of program outputgoto inside switch case case奇怪的工作

,代码:

#include<stdio.h> 
int main() 
{ 
    int n; 
    FILE *in,*out; 
    char inadd[50],outadd[50],ch; 
    readin: 

    printf("Enter the address of input file: "); 
    gets(inadd); 
    in=fopen(inadd,"r"); 
    if(in==NULL)     //reading and validating input file address 
    { 
     printf("There is an error with the opening of the file, please reenter the file name.\n"); 
     goto readin;   //readin call 
    } 
    readout: 

    printf("Enter the address of output file: "); 
    gets(outadd); 
    out=fopen(outadd,"r"); 
    if(out!=NULL)   //reading and validating output file address 
    { 
     printf("File already exists, to reenter file address enter 1 & to exit enter 2:"); 
     scanf("%d",&n); 
     switch (n)     //switc-case 
     { 
      case 1: printf("\n"); 
        goto readout; //readout call 
        break; 
      case 2: exit(0); 
     } 

    }else    //file is read and copied to input file. 
    { 
     out=fopen(outadd,"w"); 
     while(!feof(in)) 
     { 
      fscanf(in,"%c",&ch); 
      fprintf(out,"%c",ch); 
     } 
     fclose(in); 
     fclose(out); 
     printf("\n\nSuccess!\nFile copied successfully\n\n"); 
    } 
} 
+0

为什么不使用do ... while循环? –

回答

3

下面试试这个代码。原因是scanf在你的缓冲区中留下换行符并且gets选择了。

printf("File already exists, to reenter file address enter 1 & to exit enter 2:"); 
scanf("%d",&n); 
int c;  
do { 
    c = getchar(); 
}while(c != '\n' && c != EOF); 
+3

我认为应该提到,没有人应该使用'gets'。 – szczurcio