i can't find the error in my code can you guys help me? here is the code:
#include <stdio.h>
#include <string.h>
struct job
{
char jobname[50];
char jobtype;
float executingtime;
int jobpriority;
};
int main(void)
{
int n;
int i=0,j=0;
int max=0;
struct job jobdetails[n];
Then i ask the user to keyin the details of job (only jobs of Type A or Type B with Type B has higher priority than Type A)
printf("Please enter number of jobs: ");
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("\nPlease enter the job name: ");
scanf("%s",&jobdetails[i].jobname);
printf("Please enter type of job (A or B): ");
scanf("%s",&jobdetails[i].jobtype);
if (jobdetails[i].jobtype == 'A' || jobdetails[i].jobtype == 'a')
{
jobdetails[i].jobpriority=1;
}
else if (jobdetails[i].jobtype == 'B' || jobdetails[i].jobtype == 'b')
{
jobdetails[i].jobpriority=2;
}
else
{
printf("Invalid Job Type\nPlease Try Again");
return -999;
}
printf("Please enter the executing time of job (in s): ");
scanf("%f",&jobdetails[i].executingtime);
}
Here is the part which I wanna print the jobs from highest priority to lowest:
do
{
for (j=1;j<n;j++)
{
if (jobdetails[max].jobpriority < jobdetails[j].jobpriority)
{
max=j;
}
}
printf("\nJob Name: %s ",jobdetails[max].jobname);
printf("\nJob type: %c ",jobdetails[max].jobtype);
printf("\nJob Executing Time: %.f in s \n",jobdetails[max].executingtime);
max=n-1;
n=n-1;
}while (n!=0);
return 0;
}
sometimes i got the correct output but sometimes not. here is the output i got:
correct: enter image description here incorrect: enter image description here
I appreciate for your help, Thank you!
At least these problems:
Using "%s"
without a width limit
"%s"
directs input to form a string . For input like "Hello", that needs 5 + 1 (for the appended '\0'
) bytes.
char jobname[50];
...
// scanf("%s",&jobdetails[i].jobname);
scanf("%49s", jobdetails[i].jobname);
// ^ ----- Do not use & when the object is an array.
0 width is no good
The below code lacks a width, yet the width should be 0 as the location to save the string has only enough room to save the null character .
char jobtype;
...
// scanf("%s",&jobdetails[i].jobtype); // Bad
// scanf("%0s",&jobdetails[i].jobtype); // Bad too.
Here OP likely wants to read and save 1 non-white-space character.
// v- Note the space to consume optional leading white-space.
scanf(" %c",&jobdetails[i].jobtype);
or if still wanting jobtype
as a string .
char jobtype[2];
...
scanf("%1s", jobdetails[i].jobtype);
Better code checks the return value of scanf()
Did the input succeed? Find out.
if (scanf(....) != Expected_Counvertion_Count) {
Handle_Error();
}
Better code does not use scanf()
Use fgets()
to read a line of user input in a string and then parse those strings for job name, type, time, priority.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.