【问题标题】:C function call error display function using txt fileC函数调用错误显示函数使用txt文件
【发布时间】:2021-07-18 14:01:01
【问题描述】:

当我调用显示函数时,它不会在程序中调用,当我在主函数中使用它而不在函数中使用它时,它可以正常工作。

#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; 
}

知道错误是什么吗?

【问题讨论】:

  • @avm 下面说了什么。此外,您不会在 switch 语句之后指定要选择的值,这样代码就永远不会被执行。
  • 你的文字很难理解。请考虑编辑

标签: c function file dev-c++ txt


【解决方案1】:

在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; 
}

【讨论】:

  • 我在switch语句中调用了它,当用户输入1时会调用它
猜你喜欢
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
相关资源
最近更新 更多