gpt4 book ai didi

c - fputs 或 fprintf 不写入字符串文件

转载 作者:行者123 更新时间:2023-12-02 16:37:41 28 4
gpt4 key购买 nike

为什么 fputs()fprintf() 没有写入 %sfile.txt ?我尝试了这两个函数,但它们似乎没有写入文件。但是,当对 %d 使用相同的函数时,它目前确实有效。至于预期输出与当前发生的情况,请在程序中选择选项 1 并输入 2 的正方形时查看以下示例。

当前发生的事情:

1
2
4
8

预期输出:

You have chosen option: 1
The side of the square is: 2
The square area is: 4
The square perimeter is: 8

关于可能导致此问题的任何想法?谢谢!

N.b. 此代码用于学习目的,因此您可能会发现我处理变量的方式不一致(即通过引用或值传递)。请无视这一点。

#include <stdio.h> 
#include <locale.h>
#include <string.h>
#define PI 3.14

void square_functions (int side, int *square_perimeter, int *square_area);
float circle_functions (float radius, float * area_circle, float * circumference, FILE *fich);

int main()
{

float radius, area_circle, circumference;
int side, square_area, square_perimeter, choice;
FILE *fich; /* esto como variable global penaliza! */
fich=fopen("file.txt","w");

while (1)
{
printf("Enter 1 to calculate the square\n");
printf("Enter 2 to calculate the circumference\n");
printf("Enter your option:\n");
scanf("%d",&choice);
fprintf(fich,"%s\n", "You have chosen option:");
fprintf(fich,"%d\n",choice);

switch (choice)
{
case 1:
printf("Please enter the side of the square: ");
scanf("%d", &side);
fprintf(fich,"%s\n", "The side of the square is:");
fprintf(fich,"%d\n",side);
if(side > 0)
{
square_functions (side, &square_perimeter, &square_area);
printf("\nSquare area: %d", square_area);
printf("\nSquare perimeter: %d\n", square_perimeter);
fprintf(fich,"%s\n", "The square area is:");
fprintf(fich,"%d\n", square_area);
fputs("The square perimeter is",fich);
fprintf(fich,"%d\n", square_perimeter);
}
else
{
printf("The value is invalid, the operation has been cancelled");
}
break;

case 2:
printf("\n\nPlease enter the radius fo the circle: ");
scanf("%f", &radius);

if(radius > 0)
{
circle_functions (radius, &area_circle, &circumference, fich);
printf("Circle area: %f", area_circle);
printf("circumference: %f", circumference);
}
else
{
printf("The value is invalid, the operation has been cancelled");
}
break;
}
}
fclose(fich);
return 0;
}

void square_functions (int side, int *square_perimeter, int *square_area)
{
*square_perimeter = side * 4;
*square_area = side * side;
}

float circle_functions (float radius, float * area_circle, float * circumference, FILE *fich)
{
*area_circle = PI * radius * radius;
*circumference = 2 * PI * radius;
fputs("The area of the circle is",fich);
fprintf(fich,"%f\n",*area_circle);
fputs("The circumference is",fich);
fprintf(fich,"%f\n",*circumference);
return 0;
}

最佳答案

问题是您没有关闭文件。注意:您有 fclose(fich);,但无法访问。添加第三个条件,如下所示,它应该有效:

case 3:
fclose(fich);
return 0;

另一种方法是不使用无限循环 (while(1)),而是使用条件。例如:

bool run = true;
while(run)
{
...
case 3:
run = false;
break;
...
}

关于c - fputs 或 fprintf 不写入字符串文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62351035/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com