我该如何解决?它崩溃了

时间:2014-04-23 08:25:56

标签: c switch-statement

各个程序由它们自己运行,但在程序运行后会出现无效的参数 为什么会这样呢?您甚至可以通过向我展示我可以在这种情况下阅读的内容来提供帮助。感谢

#include<stdio.h>
#include<stdlib.h>

void ld_file(); //declaring functions
void mirror_file();

int main()//setting up the menu
{
    int choice;
    printf("Choose a digit between 0 and 5\n");
    scanf("%d", &choice);

    switch (choice)
    {
        case 0:{ld_file();
        break;}

        case 1:{mirror_file();
        break;}
    }
}
// Individual Programs
//**************Load file***********//
void ld_file()
{
    char ch, file_name[25];
    FILE *in;

    printf("Enter the file name\n");
    gets(file_name);
    in = fopen(file_name,"r"); // reading file
    if( in == NULL )
       {
           perror("File not found.\n");
           exit(EXIT_FAILURE);
        }
        printf("Contents of %s are:\n", file_name);

        while( ( ch = fgetc(in) ) != EOF )
            printf("%c",ch);
        fclose(in);
        return;
}

//*****************Copy File**************//
void mirror_file()
{
   char ch, orig_file[20], new_file[20];
   FILE *orig, *neo;

   printf("Enter name of file to copy\n");
   gets(orig_file);

   orig = fopen(orig_file, "r");

   if( orig == NULL )
   {
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }

   printf("Enter name of new file\n");
   gets(new_file);

   neo = fopen(new_file, "w+");
   fprintf(neo,"620048876, 23/4/14\n");

   if( neo == NULL )
   {
      fclose(orig);
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }

   while( ( ch = fgetc(orig) ) != EOF )
      fputc(ch, neo);

   printf("File copied successfully.\n");

   fclose(orig);
   fclose(neo);

   return;
}

//*********Encrypt File*******//

2 个答案:

答案 0 :(得分:3)

scanf("%d", choice);

应该是

scanf("%d", &choice);

您的开关案例应检查字符0是空字符,而不是键盘上输入0时获得的字符。

switch (choice)
{
    case '0':{ld_file();
    break;}

    case '1':{mirror_file();
    break;}

    case 'a': ; //etc..
}

答案 1 :(得分:2)

你应该在scanf中选择地址:

scanf("%d", &choice);

您的切换代码应如下所示:

switch (choice)
    {
        case 0:{ld_file();
        break;}

        case 1:{mirror_file();
        break;}
    }