【发布时间】:2020-06-14 14:36:53
【问题描述】:
我是 C 的新手,我无法弄清楚。代码编译并让我运行一次,但是当我输入它时,它给了我分段错误。我运行 gdb 并回溯它,发现分段错误在 commissionOfAMechanic (name, &percent); 中的 int main () 但我不知道如何做到这一点工作。如果有人可以给我任何类型的建议来解决该错误。我在代码中使用的文件在底部。
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
void commissionOfAMechanic (char *mechanicName, int *comm)
{
FILE * fp = fopen ("NameCommissions.txt", "r");
if ( fp == NULL )
{
printf ( "Unable to open the file\n" );
exit (-1);
}
char temp [16];
int commission;
int i;
for ( i = 0 ; i < 4 ; i++ )
{
fscanf ( fp, "%s %d", temp, *comm);
if (temp, *mechanicName)
break;
}
fclose (fp);
printf ( "The name given is %s and his commission is %d \n", temp, *comm );
}
void priceOfAllServices ( float pr[])
{
FILE * fp = fopen ( "PriceOfServices.txt", "r");
if (!fp)
{
printf ( "Can't open file.\n");
exit (-1);
}
char temp [16];
fscanf (fp, "%s %d", temp, &pr[0]);
fscanf (fp, "%s %d", temp, &pr[1]);
fscanf (fp, "%s %d", temp, &pr[2]);
fscanf (fp, "%s %d", temp, &pr[3]);
fclose (fp);
}
void getWeeklyStatsOfaMechanic (char *name, int jobs[])
{
FILE * fp = fopen ("JobsDone.txt", "r");
if (! fp)
{
printf ("Can't open file.\n");
exit (-1);
}
char temp [16];
fscanf (fp, "%s %d", temp, &jobs[0]);
fscanf (fp, "%s %d", temp, &jobs[1]);
fscanf (fp, "%s %d", temp, &jobs[2]);
fscanf (fp, "%s %d", temp, &jobs[3]);
int i;
for ( i = 0 ; i < 4 ; i++ )
{
fscanf (fp, "%s%d%d%d%d", temp, jobs[0], jobs[1], jobs[2], jobs[3]);
if (strcmp (temp, name ))
{
break;
}
}
printf ( "Jobs done by %s %d %d %d %d \n", temp, jobs[0], jobs[1], jobs[2], jobs[3]);
fclose (fp);
}
int main ()
{
int percent;
char name[16];
int jobs[4];
float prices[4];
printf ( "Please enter the name of the Mechanic\n");
scanf ("%s", name);
commissionOfAMechanic (name, &percent);
priceOfAllServices (prices);
getWeeklyStatsOfaMechanic (name, jobs);
float total = jobs[0]*prices[0] +
jobs[1]*prices[1] +
jobs[2]*prices[2] +
jobs[3]*prices[3];
printf ( "Name = %s Total Commission = %.2f\n", name, total);
return 0;
}
【问题讨论】:
-
其实应该是
fscanf ( fp, "%s %d", temp, comm);,因为comm已经是一个int指针了。 -
除此之外,您可能不想要
if (temp, *mechanicName),因为它与if (*mechanicName)相同,我想您错过了使用strcmp? -
警告你可以做
printf ( "The name given is %s and his commission is %d \n", temp, *comm );即使你没有找到,因为i达到4
标签: c linux gcc gcc-warning