【问题标题】:I keep returning the same value for variable howMany我一直为变量 howMany 返回相同的值
【发布时间】: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 相同的结果?非常感谢您的任何想法。

【问题讨论】:

  • 你很幸运。在您的计算机上,有一个称为“调试器”的工具,它可以让您单步执行代码,一次一行,并检查所有变量的值。在调试器的帮助下,当它逐步执行循环时,您应该能够立即找出问题所在。

标签: c++ file struct header


【解决方案1】:

我目前没有要验证的计算机,但有一行提示我,因为这是一个常见错误(至少对我而言):

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

你也可以使用all_info+i 来达到同样的效果。

【讨论】:

  • 谢谢!我的变量 person、key 和 offset 的值似乎都随着每次迭代而变化,但是 howMany 的值每次都保持不变地返回到调用例程?
  • 只是为了让您知道我发现了问题。在我的函数 nonZeroes 中(在函数的末尾)我关闭了文件指针,因此每次新的迭代都会关闭文件指针。我的问题是我应该在每次迭代结束时保持文件打开还是关闭,然后在 main() 中最后关闭并重新打开?
猜你喜欢
  • 2015-05-21
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多