我一直为变量howMany返回相同的值

I keep returning the same value for variable howMany

本文关键字:返回 howMany 一直 变量      更新时间:2023-10-16

我有一个以前已经填充了数据的文件。该文件由一组结构组成。每个结构代表一个回合,每个阵列位置代表一个人最多20个回合。我的.h文件:

define READTWENTY_H
class readTwenty {
public:
readTwenty();
void nonZeroes(int, int &);
struct a_round {
int score;
double course_rating;
int slope;
char date[15];
char place[40];
char mark[1];
}; //end structure definition
struct a_round all_info[20];
FILE *fptr;
}; //end class
#endif

在数据文件中,有些"轮次"中有实际数据,有些以前用零填充。我想数零轮。我有一个循环,在这个循环中我可以请求另一个"person"值来查看。这个值被发送到一个函数,在该函数中,通过引用一个名为"howMany"的变量来确定零轮数并返回。

// readMember.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"
#include <iostream>
#include "readTwenty.h"
using namespace std;
int main()
{
int person = 0;
readTwenty personData;
int howMany = 0;
while (person != -999) {
cout << "Which member (keyfield)  would you like to see? -999 to stop ";
cin >> person;
if (person == -999)
exit(0);
personData.nonZeroes(person-1, howMany);
cout << "The number of non-zero values for this member is " << howMany << endl;
}//end while
return 0;
}

一旦作为"键"发送到非零函数,我会在文件中创建一个偏移量,读取该个体的20轮,并通过引用将count的值返回到变量howMany中的调用例程。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "readTwenty.h"
#include <errno.h>
#include <cstdio>
readTwenty::readTwenty() {
const char *configfile;
configfile = "scores.dat";
#ifdef WIN32
errno_t err;
if((err = fopen_s(&fptr,configfile, "rb")) != 0)
#else
if ((fp_config = fopen(configfile, "rb")) == NULL)
#endif
fprintf(stderr, "Cannot open cinfig file %s!n", configfile);
}//end constructor
void readTwenty::nonZeroes(int key, int &count) {
int zeroes = 0;
int offset = key * ((sizeof(all_info[0]) * 20));
fseek(fptr, offset, SEEK_SET);
for (int i = 0; i < 20; i++){
fread(&all_info[i], sizeof(all_info[0]), 1, fptr);
if (all_info[i].score == 0)
zeroes++;
all_info[i].mark[0] = ' ';
}//end for loop
count = 20 - zeroes;
fclose(fptr);
}//end of function nonZeroes

问题是,我给person的第一个值返回的是正确的非零回合数。然而,while循环的每一次后续迭代,无论我给person的第二个值是多少,都会得到与第一个person相同的结果?如果您有任何想法,我将不胜感激。

我目前没有要验证的计算机,但有一行跳出来,因为这是一个常见错误(至少对我来说):

fread的第一个参数是&all_info[i];你可能想要&(all_info[i]),但编译器并不是这样理解的——&[i]更强,所以你得到了(&all_info)[i]

您也可以使用all_info+i来获得相同的效果。