Unable to read characters in the file

Asked 2 years ago, Updated 2 years ago, 35 views

to knap10.txt
10
39.0 13.0 68.0 15.0 10.0 20.0 31.0 15.0 41.0 16.0
42.0 12.0 45.0  5.0  2.0 61.0 89.0 32.0 47.0 18.0

I typed in a number, but I couldn't read it.
By the way, I did the following program.

#include<stdio.h>
# include <string.h>
# include <stdlib.h>

constint NMOJI=50;
constint MAX_ITEM=100;

int main()
{
    FILE*fp;
    inti,j;
    intitem;
    double capacity;
    double weight [MAX_ITEM], value [MAX_ITEM];
    char file_name [NMOJI];
    printf("Data Fly Name:");
    scanf("%s", file_name);
    if(((fp=fopen(file_name, "r"))==NULL){
        printf("%s: The file cannot be opened.\n", file_name);
        return-1;
    }
    printf("Knapsack capacity:"; scanf("%lf", & capacity);
    printf("data filename:%s\n", file_name);
    printf("nappack capacity: %f\n", capacity); 
    printf("\n");
   
    fscanf(fp, "%d", & nitem);
    if(nitem>MAX_ITEM){
        printf("Please set the number of items to %3d or less.\n", MAX_ITEM);
        return-1;
    } 
    for (i=0; i<nitem;i++)
        fscanf(fp, "%lf", & weight[i]);
    for (i=0; i<nitem;i++)
        fscanf(fp, "%lf", & value[i]);
    fclose(fp);
  
    return 0;
}

where fscanf(fp, "%d", &nitem); the top 10 is

 for (i=0; i<nitem;i++)
        fscanf(fp, "%lf", & weight[i]);
    for (i=0; i<nitem;i++)
        fscanf(fp, "%lf", & value[i]);

So, I thought I could read the weight of the second level from the top and the value of the bottom, but somehow the result was

$./a.out
Data Fly Name: knap10.txt
Knapsack capacity: 121
Data File Name: knap10.txt
Knapsack Capacity: 121.000000

It only appears.I thought the fscanf function was to read the characters in the file, so I didn't know what was wrong.Why can't I read the numbers in the file?

c

2022-09-30 11:04

1 Answers

Perhaps the file loading was successful.It is normal to end with the line "Napsack Capacity" because nothing is displayed after a successful load.

In order to determine if the load was successful, why don't you modify the code as follows?

if(fscanf(fp, "%d", &nitem)!=1){
    fprintf(stderr, "Number of items could not be read\n";
    return EXIT_FAILURE;
  }
  if(nitem>MAX_ITEM){
    fprintf(stderr, "Please keep item count below %3d.\n", MAX_ITEM);
    return EXIT_FAILURE;
  }
  for(i=0;i<nitem;i++){
    if(fscanf(fp, "%lf", & weight[i])!=1){
      fprintf(stderr, "%dth weight value could not be read.\n", i+1);
      return EXIT_FAILURE;
    }
  }
  for(i=0;i<nitem;i++){
    if(fscanf(fp, "%lf", & value[i]))!=1){
      fprintf(stderr, "%dth value value could not be read.\n", i+1);
      return EXIT_FAILURE;
    }
  }
  fclose(fp);
  printf("%d Item Load Completed.\n",nitem);


2022-09-30 11:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.