[英]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.