试图读取文件并将第一输入存储在数组val中,第二输入存储在数组wt(权重)中

问题描述 投票:0回答:1

我需要读入一个名为“ data.txt”的文件,并将第一个输入作为值存储,将第二个相应的输入作为权重存储。我在读取它们并存储值时遇到问题。

data.txt (example)

3 25
2 20
1 15
4 40
5 50

这是我开始的目的:

FILE *myFile;
myFile=fopen("data.txt", "r");


int val[20]={0}; //initialize value array to zero
int wt[20]={0}; 
int W=80; //Set capacity to 80
int i;
int n;

while(!feof(myFile)){ 
  fscanf(myFile, "%1d%1d", &val[i], &wt[i]);
}

n = sizeof(val)/sizeof(val[0]);
printf("%d", knapSack(W, wt, val, n));//prints out the maximum value
fclose(myFile);
return 0;

我已经将上面的代码编辑为以下代码:

FILE *myFile;
myFile=fopen("data.txt", "r");


int val[20]={0};
int wt[20]={0};
int W=80; //Set capacity to 80
int i;
int n;

for(i=0;i<sizeof(val);i++){
  fscanf(myFile, "%1d%1d", &wt[i],&val[i]);
}

n = sizeof(val)/sizeof(val[0]);
printf("%d", knapSack(W, wt, val, n));//prints out the maximum value
fclose(myFile);
return 0;

当我使用data.txt示例中的输入时,它始终输出55。

c arrays scanf fopen feof
1个回答
0
投票

您遇到的最大问题是,您无法通过读取本身的返回来控制读取循环。例如,在您的情况下,您需要:

int i = 0;
while (fscanf(myFile, "%1d%1d", &wt[i],&val[i]) == 2)
    i++;

读取结束时,i将保存读取到数组中的元素数。

(<< [note:您不能正确使用任何输入函数,除非您检查返回内容

[而不是将值读入单独的数组中,每当您将多个值作为一个对象进行协调时(例如,每个valwt对),您都应该考虑struct。这样,您就可以将两个值作为一个对象进行协调。

您的情况下一个简单的例子可能是:

#include <stdio.h> #define MAXVAL 20 /* if you need a constant, #define one (or more) */ typedef struct { /* struct with int val, wt + typdef for conveninece */ int val, wt; } mydata; int main (int argc, char **argv) { size_t n = 0; /* number of elements read */ mydata arr[MAXVAL] = {{ .val = 0 }}; /* array of mydtate */ /* use filename provided as 1st argument (stdin by default) */ FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin; if (!fp) { /* validate file open for reading */ perror ("file open failed"); return 1; } /* read all pairs of values in file into array */ while (fscanf (fp, "%d %d", &arr[n].val, &arr[n].wt) == 2) n++; if (fp != stdin) /* close file if not stdin */ fclose (fp); for (size_t i = 0; i < n; i++) /* output values */ printf ("arr[%zu] %2d %2d\n", i, arr[i].val, arr[i].wt); }

上面,代码的作用与我在成功从文件中读取一对值时限制读取循环的建议相同。唯一的区别是在结构中协调valwt值。

示例使用/输出

将数据保存在文件dat/val_wt.txt中,您将收到以下输出:

$ ./bin/read_val_wt dat/val_wt.txt arr[0] 3 25 arr[1] 2 20 arr[2] 1 15 arr[3] 4 40 arr[4] 5 50

虽然上面我们直接用fscanf进行读取,但您可以通过先将每一行读入一个字符数组,然后用sscanf解析该字符数组中的所需值,使读取过程更加健壮。本质上,您在做同样的事情,但是通过使用fgets/sscanf,您可以对(1)行的读取进行独立验证; (2)从行中解析所需信息。如果行格式错误,则可以防止

matching-failure

影响输入文件中其余行的读取。仔细检查,如果还有其他问题,请告诉我。
© www.soinside.com 2019 - 2024. All rights reserved.