【发布时间】:2016-06-12 00:34:52
【问题描述】:
我有一个先前已填充数据的文件。该文件由一组结构组成。每个结构代表一轮,每个阵列位置代表一个人最多 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
在数据文件中,一些“回合”中有实际数据,而一些之前已经用零填充。我想计算零轮。我有一个循环,我可以在其中要求查看另一个“人”值。该值被发送到一个函数,在该函数中确定零轮数,并通过引用名为“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;
}
一旦作为“key”发送到 nonzeroes 函数,我会在文件中创建一个偏移量,并为该个人读取 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 的第一个值返回了正确的非零轮数。但是,无论我为 person 提供的第二个值如何,while 循环的每次后续迭代都会返回与第一个 person 相同的结果?非常感谢您的任何想法。
【问题讨论】:
-
你很幸运。在您的计算机上,有一个称为“调试器”的工具,它可以让您单步执行代码,一次一行,并检查所有变量的值。在调试器的帮助下,当它逐步执行循环时,您应该能够立即找出问题所在。