Here's my code and output of my variables: What else do I need to add to my while loop so that I can have my variables and methods work.
int main() {
FILE *ifp;
ifp = fopen("processes.txt","r");
if(ifp == NULL) {
printf("Error Opening file.\n");
exit(1);
}
char str[100];
int i=0;
while(fgets(str, 100, ifp) != NULL) {
fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].rank);
i++;
}
}
printf("ProceId AT duration rank\n");
for (int j = 0; j < i - 1; ++j){
printf("%d\t%0.1f\t%d\t%d\n",arr[j].pid,arr[j].AT,arr[j].duration,arr[j].rank );
}
ProceId AT duration rank
1398 0.0 0 0
2306 0.0 0 0
3219 0.0 0 0
4478 0.0 0 0
5653 0.0 0 0
6399 0.0 0 0
7777 0.0 0 0
Here is the file which has a line of strings that i don't need which is why i used fgets.
ProcessID ArrTime Duration Rank
1398 1.0 16 3
2306 4.5 6 7
3219 3.0 11 1
4478 2.0 3 5
5653 3.5 7 2
6399 4.0 8 6
7777 2.5 17 8
Change this:
fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].rank);
to this:
fscanf(ifp," %d %f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].rank);
since you were using an invalid conversion specifier.
Pay attention to the compiler warnings next time, they usually tell the whole story:
warning: invalid conversion specifier '.'
[-Wformat-invalid-specifier]
fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].d...
~~~^
warning: format specifies type 'int *' but the argument has type
'float *' [-Wformat]
fscanf(ifp," %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].d...
~~ ^~~~~~~~~~
%f
warning: data argument not used by format string
[-Wformat-extra-args]
..." %d %0.1f %d %d", &arr[i].pid, &arr[i].AT, &arr[i].duration, &arr[i].ra...
~~~~~~~~~~~~~~~~~ ^
The warnings suggest that because of the invalid conversion specifier, the %d
format specifier is used for the float field of your struct (named AT
), and then everything becomes a mess, since you are short by one format specifier...
Read more in How to only accept a certain precision (so many decimals places) in scanf?
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.