我一直为变量howMany返回相同的值
I keep returning the same value for variable howMany
我有一个以前已经填充了数据的文件。该文件由一组结构组成。每个结构代表一个回合,每个阵列位置代表一个人最多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
来获得相同的效果。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 我一直为变量howMany返回相同的值