C函数调用错误显示函数使用txt文件

问题描述

当我调用显示函数时,它不会在程序中调用,而当我在主函数中使用它而不在函数中使用它时,它工作得很好。

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main() 
{
int d;
int choose;
int display();
printf("enter 1 to display and 2 to quit\n");
 switch(choose)
{
    case 1:
    display();
    break;
    
}
scanf("%s",choose);
int display();
system("cls");
}
int display()
{
char fname[20],str[500];
FILE *fp;
printf("Enter the Name of File: ");
gets(fname);
fp = fopen(fname,"r");
if(fp==NULL)
    printf("Error Occurred while opening the File!");
else
{
    fscanf(fp,"%[^\0]",str);
    printf("\nContent of File is:\n\n");
    printf("%s",str);
}
fclose(fp);
getch();
  return 0; 
}

知道错误是什么吗?

解决方法

main() 中,您没有调用 display() 函数,而是重新声明(int display())它。 声明一个函数和调用它是有区别的。

函数声明:int display()

函数调用:display();

声明只是告诉程序一个函数的存在。如果你想调用一个函数,那就进行函数调用。

编辑: 你的问题框架很差,很难理解。我猜你在问-

为什么 switch 语句中的函数调用没有执行?

有两个原因-

1.首先,您没有为 choose 中使用的 switch 变量分配任何值(@Nicholas 也指出)。

2.scanf(...) 语句放置错误,语法也错误。 Read here

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main() 
{
int d;
int choose;
int display();
printf("enter 1 to display and 2 to quit\n");
scanf("%d",&choose); //assigning value to 'choose'.
 switch(choose)
{
    case 1:
    display();
    break;
    default: break; //always use a default case for handling wrong input.
}
//int display(); //idk why you're redeclaring it,there is no need. If you're making a function call then remove `int` from syntax.
system("cls");
return 0;
}
int display()
{
char fname[20],str[500];
FILE *fp;
printf("Enter the Name of File: ");
gets(fname);
fp = fopen(fname,"r");
if(fp==NULL)
    printf("Error Occurred while Opening the File!");
else
{
    fscanf(fp,"%[^\0]",str);
    printf("\nContent of File is:\n\n");
    printf("%s",str);
}
fclose(fp);
getch();
  return 0; 
}