[英]C programming: I'm having trouble with 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];
然后我要求用户输入工作的详细信息(只有 A 类或 B 类的 B 类工作的优先级高于 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);
}
这是我想从最高优先级到最低优先级打印作业的部分:
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;
}
有时我得到了正确的 output 但有时没有。 这是我得到的 output:
感谢您的帮助,谢谢!
至少有这些问题:
使用没有宽度限制"%s"
"%s"
指示输入形成一个字符串。 对于像“Hello”这样的输入,需要 5 + 1(对于附加'\0'
)字节。
char jobname[50];
...
// scanf("%s",&jobdetails[i].jobname);
scanf("%49s", jobdetails[i].jobname);
// ^ ----- Do not use & when the object is an array.
0宽度不好
下面的代码缺少宽度,但宽度应该为 0,因为保存字符串的位置只有足够的空间来保存null 字符。
char jobtype;
...
// scanf("%s",&jobdetails[i].jobtype); // Bad
// scanf("%0s",&jobdetails[i].jobtype); // Bad too.
在这里,OP 可能想要读取并保存 1 个非空白字符。
// v- Note the space to consume optional leading white-space.
scanf(" %c",&jobdetails[i].jobtype);
或者如果仍然想要jobtype
作为string 。
char jobtype[2];
...
scanf("%1s", jobdetails[i].jobtype);
更好的代码检查scanf()
的返回值
输入成功了吗? 查出。
if (scanf(....) != Expected_Counvertion_Count) {
Handle_Error();
}
更好的代码不使用scanf()
使用fgets()
读取字符串中的一行用户输入,然后解析这些字符串以获取作业名称、类型、时间、优先级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.