Having a problem in making a dynamic box using these set of ASCII codes. I'm really lost on what to do. This dynamic box also has numbers inside them.
I already tried making loops inside loops to adjust the box's size.
int main(){
char asciis[] = {'\xDA','\xB3','\xC3','\xC0','\x20','\xC4','\xC5','\xC1','\xBF','\xB4','\xD9', '\xC2'};
int box size = (n*2)+1;
char box[box size][box size]; //set the size of the box
//set a in all coordinates
/*for (int r = 0; r < n; r++){
for (int c = 0; c < n; c++){
box[r][c] = 'a';
}
}*/
for (int r = 0; r < n; r++){
for (int c = 0; c < n; c++){
for (int boxrow = 0; boxrow < box size; boxrow++){
for (int boxcol = 0; boxcol < box size; boxcol++){
//conditions
}
}
}
cout << endl;
}
}
This is the output I'm trying to create:
https://i.imgur.com/YRgMlaJ.png
Don't mind those numbers, I was just mapping the array.
I'm sure there's a simpler solution, but off the top of my head:
#include <iostream>
using namespace std;
enum BoxParts {
kLeftUpper = '\xDA',
kVertical = '\xB3',
kLeftBreak = '\xC3',
kLeftLower = '\xC0',
kEmpty = '\x20',
kHorizontal = '\xC4',
kIntersection = '\xC5',
kBottomBreak = '\xC1',
kRightUpper = '\xBF',
kRightBreak = '\xB4',
kRightLower = '\xD9',
kTopBreak = '\xC2',
kCount = 12
};
void drawLine(const int cellCount, const int cellWidth, const char left, const char divider, const char contents, const char right)
{
cout << left;
for (int i = 1; i < cellCount * cellWidth; ++i)
{
if (0 == i % cellWidth)
cout << divider;
else
cout << contents;
}
cout << right << endl;
}
void drawBox(const int cellCount, const int cellWidth, const int cellHeight)
{
// top
drawLine(cellCount, cellWidth, kLeftUpper, kTopBreak, kHorizontal, kRightUpper);
for (int i = 1; i < cellCount * cellHeight; ++i)
{
if (0 == i % cellHeight)
drawLine(cellCount, cellWidth, kLeftBreak, kIntersection, kHorizontal, kRightBreak);
else
drawLine(cellCount, cellWidth, kVertical, kVertical, ' ', kVertical);
}
// bottom
drawLine(cellCount, cellWidth, kLeftLower, kBottomBreak, kHorizontal, kRightLower);
}
int main(int argc, char** argv) {
const int n = 4;
drawBox(n, 10, 5);
getchar();
return 0;
}
Produces:
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm am trying to dynamically make 2d arrays that are then supposed to be iterated through to check their contents. Whenever I try to use a function that indexes the array I get a segmentation fault. The two functions that are creating the problems are the printg() and get() functions. I'm not sure exactly what I'm doing wrong, but neither of them will work properly for me.
Any help would be great. Thank you.
#ifndef _GRID_H
#define _GRID_H
#include <iostream>
using namespace std;
class Grid
{
public:
Grid();
Grid(const Grid& g2);
Grid(int x, int y, double density);
Grid(string file);
~Grid();
bool check(int x, int y); //check if a cell is inhabited or not
bool isEmpty();//check if a grid is living
bool equals(const Grid& g2);//checks if two grids are equal
void kill(int x, int y);//kill a cell
void grow(int x, int y);//grow a cell
int getSize();
int getNumRows();
int getNumCol();
int getNumLiving();
void printg(int r, int c);
char get(int x, int y) const;
private:
int size; //number of cells in grid
int row; //row length (number of columns)
int column; //column length (number of rows)
int num_living; //number of X's in the grid
char** myGrid;
};
#endif
#include "Grid.h"
#ifndef _GRID_C
#define _GRID_C
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
//compile with g++ -I /home/cpsc350/GameOfLife Grid.cpp
using namespace std;
Grid::Grid() //do i need a default constructor????
{
char myGrid[10][10] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
row = 10;
column = 10;
size = 100;
}
Grid::Grid(const Grid& g2)//copy constructor/////////////help
{
size = g2.size;
row = g2.row;
column = g2.column;
num_living = g2.num_living;
char** myGrid = new char*[row];
for(int i = 0; i < row; i++)
myGrid[i] = new char[column];
for(int i1 = 0; i1 < row; i1++)
{
for(int i2 = 0; i2 < column; i2++)
{
//copy(&g2[i1][i2], &g2[i1][i2]+row*column,&myGrid[i1][i2]);
myGrid[i1][i2] = g2.get(i1,i2);
}
}
}
Grid::Grid(int x, int y, double density)
{
char** myGrid = new char*[x];
for(int i = 0; i < x; i++)
myGrid[i] = new char[y];
row = x;
column = y;
size = x*y;
num_living = size * density;
string str = "";
for(int a = 0; a < num_living; a++)//adds the density of X's to a string
{
str += 'X';
}
for(int a = 0; a < size - num_living; a++)//adds the rest to the string
{
str += '-';
}
int randnum;
//randomly generates indicies in the string str and puts them into the array
for(int i1 = 0; i1 < column; i1++)
{
for(int i2 = 0; i2 < row; i2++)
{
//generate random numbers from index 0 to length of string - 1
if(str.length()>1)
{
randnum = (rand()%(str.length()-1))+1;
}
else
{
randnum = 0;
}
myGrid[i1][i2] = str[randnum];
str.erase(randnum);
}
}
}
Grid::Grid(string file)
{
num_living = 0;
//code to create a 2d array from a filepath
ifstream openfile(file);
//error handling
if(! openfile)
{
cout << "Error, file could not be opened" << endl;
exit(0);
}
openfile >> column;//gets number of rows
openfile >> row;//gets number of columns
size = row*column;
char** myGrid = new char*[row];
for(int i = 0; i < row; i++)
myGrid[i] = new char[column];
for(int x = 0; x<column; x++)
{
for(int y = 0; y<row; y++)
{
openfile >> myGrid[x][y];
if(! openfile)//error handling
{
cout << "Error reading file at " << row << "," << column << endl;
}
if(myGrid[x][y] == 'X')
{
num_living++;
}
}
}
openfile.close();
}
Grid::~Grid()
{
if(myGrid)
{
for(int i = 0; i < row; i++)
{
delete []myGrid[i];
}
delete []myGrid;
}
}
void Grid::kill(int x, int y)
{
if(myGrid[x][y] == 'X')
{
num_living--;
}
myGrid[x][y] = '-';
}
void Grid::grow(int x, int y)
{
if(myGrid[x][y] == '-')
{
num_living++;
}
myGrid[x][y] = 'X';
}
bool Grid::check(int x, int y)
{
if(y<0 || x<0)
{
return(false);
}
return (myGrid[x][y] == 'X');
}
bool Grid::isEmpty()
{
return (num_living == 0);
}
bool Grid::equals(const Grid& g2)
{
if(size != g2.size) //checks if sizes are equal
{
return false;
}
if(row != g2.row)//checks if numRows are equal
{
return false;
}
if(column != g2.column)//checks if numCol are equal
{
return false;
}
if(num_living != g2.num_living)//checks if numliving are equal
{
return false;
}
for(int x = 0; x < row; x++)//checks each element
{
for(int y = 0; y < column; y++)
{
if(myGrid[x][y] != g2.get(x,y))
{
return false;
}
}
}
return true;
}
int Grid::getSize()
{
return(size);
}
int Grid::getNumRows()
{
return(column);
}
int Grid::getNumCol()
{
return(row);
}
int Grid::getNumLiving()
{
return(num_living);
}
void Grid::printg(int r, int c)
{
for(int x = 0; x < r; x++)
{
for(int y = 0; y < c; y++)
{
cout << myGrid[x][y];
}
cout << endl;
}
}
char Grid::get(int x, int y) const
{
return myGrid[x][y];
}
#endif
The problem that I see at first is that both your default and copy constructor do not initialize myGrid. what you are doing in them will create an additional array with the same name which 'shadows' myGrid. instead you have to do:
Grid::Grid(const Grid& g2)
{
size = g2.size;
row = g2.row;
column = g2.column;
num_living = g2.num_living;
myGrid = new char*[row]; // removed "char**" at the start of this line
for(int i = 0; i < row; i++)
myGrid[i] = new char[column];
for(int i1 = 0; i1 < row; i1++)
{
for(int i2 = 0; i2 < column; i2++)
{
//copy(&g2[i1][i2], &g2[i1][i2]+row*column,&myGrid[i1][i2]);
myGrid[i1][i2] = g2.get(i1,i2);
}
}
}
your default constructor has the same problem. but note that you can't initialize it with braces. but you don't have to have a default constructor if you are not using it.
I am trying to use the suggestion from this post to free up time being spent in _platform_memmove$VARIANT$Haswell. According to a time profiler, this is occurring when I send a pointer to several class instances to a function. I have tried changing the way I declare the class instances, changing what the function takes, etc. but have not been able to resolve this.
The chunk of my code that may help:
Inputs *tables = new Inputs(OutputFolder, DataFolder);
ScreenStrat *strat_burnin = new ScreenStrat(ScreenStrat::NoScreen, ScreenStrat::NoScreen,
tables->ScreenStartAge, tables->ScreenStopAgeHIV,
tables->ScreenStopAge, ScreenStrat::NoVaccine);
calibrate *calib_output = new calibrate ();
StateMachine *Machine = new StateMachine();
for (int i = 0; i < n_sims; i++){
calib_output->saved_output[i] = RunCalibration(calib_output->calib_params[i], *strat_burnin, *tables, *Machine);
}
auto ret_val = *calib_output;
delete strat_burnin;
delete tables;
delete Machine;
delete calib_output;
return(ret_val);
and then the function declaration:
vector<double> RunCalibration(vector<double> calib_params, ScreenStrat &strat_burnin, Inputs &tables, StateMachine &Machine)
EDIT
I addressed the points #Botje suggest and it hasn't fixed the problems. Updated code:
void RunCalibration(calibrate &calib, ScreenStrat &strat_burnin, Inputs &tables, StateMachine &Machine, int i);
unique_ptr<calibrate> RunChain(string RunsFileName, string CurKey, string OutputFolder, string DataFolder);
int main(int argc, char* argv[]) {
string DataFolder;
string OutputFolder;
DataFolder = "../Data/";
OutputFolder = "../Output/";
unsigned int run;
string CurKey;
string RunsFileName(DataFolder);
if(argc == 1){
RunsFileName.append("test.ini");
}
else if(argc > 1){
RunsFileName.append(argv[1]);
}
CIniFile RunsFile(RunsFileName);
if (!RunsFile.ReadFile()) {
cout << "Could not read Runs File: " << RunsFileName << endl;
exit(1);
}
CurKey = RunsFile.GetKeyName (0);
if (RunsFile.GetValue(CurKey, "RunType") == "Calibration"){
int totaliters = RunsFile.GetValueI(CurKey, "Iterations");
int n_sims = RunsFile.GetValueI(CurKey, "Simulations");
vector<future<unique_ptr<calibrate>>> futures;
vector<unique_ptr<calibrate>> modeloutputs;
for (run = 0; run < totaliters; run++){
futures.push_back (async(launch::async, RunChain, RunsFileName, CurKey, OutputFolder, DataFolder));
}
for (int i = 0; i < futures.size(); i++){
modeloutputs.push_back (futures[i].get());
} return(0)}
unique_ptr<calibrate> RunChain(string RunsFileName, string CurKey, string OutputFolder, string DataFolder) {
Inputs *tables = new Inputs(OutputFolder, DataFolder);
tables->loadRFG (RunsFileName, CurKey);
tables->loadVariables ();
int n_sims = tables->Simulations;
int n_params = tables->Multipliers.size();
int n_targs = tables->CalibTargs.size();
ScreenStrat *strat_burnin = new ScreenStrat(ScreenStrat::NoScreen, ScreenStrat::NoScreen,
tables->ScreenStartAge, tables->ScreenStopAgeHIV,
tables->ScreenStopAge, ScreenStrat::NoVaccine);
calibrate *calib_output = new calibrate (n_sims, n_params, n_targs);
calib_output->multipliers_names = tables->MultipliersNames;
calib_output->calib_targs_names = tables->CalibTargsNames;
for (int i = 0; i < n_targs; i ++){
calib_output->calib_targs[i] = tables->CalibTargs[i][0];
calib_output->calib_targs_SD[i] = tables->CalibTargs[i][1];
}
for (int i = 0; i < n_params; i++){
for (int j = 0; j < 3; j++){
calib_output->multipliers[i][j] = tables->Multipliers[i][j];
}
}
StateMachine *Machine = new StateMachine();
for (int i = 0; i < n_sims; i++){
RunCalibration(*calib_output, *strat_burnin, *tables, *Machine, i);
}
unique_ptr<calibrate> ret_val = make_unique<calibrate>(*calib_output);
delete strat_burnin;
delete tables;
delete Machine;
delete calib_output;
return(ret_val);
}
void RunCalibration(calibrate &calib, ScreenStrat &strat_burnin, Inputs &tables, StateMachine &Machine, int i){
Adding in Calibrate definition per request from #botje
#include "calibrate.h"
using namespace std;
calibrate::calibrate(int n_sims, int n_params, int n_targs) {
calib_targs.resize (n_targs);
calib_targs_SD.resize (n_targs);
multipliers.resize(n_params);
for(int i = 0; i < n_params; i++){
multipliers[i].resize(3);
}
calib_params.resize (n_sims);
for (int i = 0; i < calib_params.size(); i++){
calib_params[i].resize (n_params);
}
saved_output.resize (n_sims);
for (int i = 0; i < saved_output.size(); i++){
saved_output[i].resize (n_targs);
}
best_params.resize (n_params);
GOF.clear();
tuned_SD.resize(n_params);
}
calibrate::~calibrate(void) {
}
void calibrate::CalculateGOF(int n_sims) {
GOF.push_back (WeightedDistance (saved_output[n_sims][0], calib_targs[0], calib_targs_SD[0]));
for (int i = 1; i < calib_targs.size(); i ++){
GOF[n_sims] += WeightedDistance (saved_output[n_sims][i], calib_targs[i], calib_targs_SD[i]);
}
if (n_sims == 0){
GOF_min = GOF[0];
best_params = calib_params[0];
} else {
auto it = std::min_element(std::begin(GOF), std::end(GOF));
int index = distance(GOF.begin(), it);
GOF_min_run = GOF[index];
if (GOF_min_run < GOF_min){
GOF_min = GOF_min_run;
best_params = calib_params[index];
}
}
}
std::vector<double> calibrate::loadCalibData(int n_params, int n_sim, int tuning_factor) {
if(n_sim == 0){
random_device rd;
mt19937 gen(rd());
for (int i = 0; i < n_params; i ++ ){
uniform_real_distribution<> dis(multipliers[i][0], multipliers[i][1]);
calib_params[n_sim][i] = dis(gen);
}
} else {
tuned_SD = tuningparam (n_sim, n_params, tuning_factor);
for (int i = 0; i < n_params; i ++ ){
calib_params[n_sim][i] = rnormal_trunc (best_params[i], tuned_SD[i], multipliers[i][1], multipliers[i][0]);
}
}
return(calib_params[n_sim]);
}
double calibrate::WeightedDistance(double data, double mean, double SD) {
double distance = pow((data - mean)/(SD * 2),2);
return distance;
}
double calibrate::rnormal_trunc(double mu, double sigma, double upper, double lower) {
std::default_random_engine generator;
std::normal_distribution<double> distribution(mu, sigma);
double prob = distribution(generator);
while (prob < lower || prob > upper){
prob = distribution(generator);
}
return(prob);
}
vector<double> calibrate::tuningparam(int n_sims, int n_param, int tuning_factor) {
vector<double> newSD;
for (int i = 0; i < n_param; i++){
newSD.push_back (multipliers[i][2]/pow(tuning_factor,n_sims));
}
return newSD;
}
I improved RunCalibration as follows. Note the comments for further improvement opportunities.
using std::make_unique;
using std::unique_ptr;
void RunCalibration(calibrate &calib, ScreenStrat &strat_burnin, Inputs &tables, StateMachine &Machine, int i);
unique_ptr<calibrate> RunChain(string RunsFileName, string CurKey, string OutputFolder, string DataFolder) {
auto tables = make_unique<Inputs>(OutputFolder, DataFolder);
tables->loadRFG (RunsFileName, CurKey);
tables->loadVariables ();
int n_sims = tables->Simulations;
int n_params = tables->Multipliers.size();
int n_targs = tables->CalibTargs.size();
auto strat_burnin = make_unique<ScreenStrat>(
ScreenStrat::NoScreen, ScreenStrat::NoScreen,
tables->ScreenStartAge, tables->ScreenStopAgeHIV,
tables->ScreenStopAge, ScreenStrat::NoVaccine);
auto calib_output = make_unique<calibrate>(n_sims, n_params, n_targs);
// I don't know the type of these fields, but IF you do not modify them in
// `RunCalibration`, consider making them `shared_ptr<vector<...>>`
// both in `calibrate` and in `Inputs` so you can simply copy
// the pointer instead of the full table.
calib_output->multipliers_names = tables->MultipliersNames;
calib_output->calib_targs_names = tables->CalibTargsNames;
// Same applies here. If you do not modify CalibTargs, make `calib_targs` a shared_ptr
// and only copy by pointer.
for (int i = 0; i < n_targs; i ++){
calib_output->calib_targs[i] = tables->CalibTargs[i][0];
calib_output->calib_targs_SD[i] = tables->CalibTargs[i][1];
}
// and again...
for (int i = 0; i < n_params; i++){
for (int j = 0; j < 3; j++){
calib_output->multipliers[i][j] = tables->Multipliers[i][j];
}
}
auto Machine = make_unique<StateMachine>();
for (int i = 0; i < n_sims; i++){
RunCalibration(*calib_output, *strat_burnin, *tables, *Machine, i);
}
// This will return the unique_ptr without copying.
return calib_output;
}
am new to c++ and am trying to create a burning forest simulator. I have been trying to call a function from the forest class but i dont know how to give it an argument, if anyone could help that would be great here is the code that i have at the moment.
using namespace std;
class ForestSetup
{
private:
const char Tree = '^';
const char Fire = '*';
const char emptySpace = '.';
const char forestBorder = '#';
const int fireX = 10;
const int fireY = 10;
char forest[21][21];
public:
void CreateForest()
{
// this function is to create the forest
for (int i = 0; i < 21; i++) // this sets the value of the rows from 0 to 20
{
for (int j = 0; j < 21; j++) // this sets the value of the columns from 0 to 20
{
if (i == 0 || i == 20)
{
forest[i][j] = forestBorder; // this creates the north and south of the forest border
}
else if (j == 0 || j == 20)
{
forest[i][j] = forestBorder; // this creates the east and the west forest border
}
else
{
forest[i][j] = Tree; // this filles the rest of the arrays with trees
}
}
}
forest[fireX][fireY] = Fire; // this sets the fire in the middle of the grid
}
void ShowForest(char grid[21][21])
{
for (int i = 0; i < 21; i++)
{
for (int j = 0; j < 21; j++)
{
cout << grid[i][j];
}
cout << endl;
}
}
};
int main(void)
{
ForestSetup myForest;
myForest.ShowForest();
system("Pause");
return 0;
}
Let's say you have a setOnFire function with the x and y co-ordinates of where you want to start the fire.
public:
setOnFire(int x, int y)
{
// Code to flag that part of the forest on fire
}
In your main, you would call it with
myForest.setOnFire(5,5);
Within the ForestSetup class you just need setOnFire(5,5);
This tutorials point article might help.
The following code is giving me the following error
Error description :
Unhandled exception at 0x00DC5D81 in ImageComponent2.exe: 0xC0000005: Access violation reading location 0xCDCDCDD5.
// ImageComponents
#include <iostream>
#include "Position.h"
using namespace std;
void labelComponents(int size, int **pixel);
void outputImage(int size, int **pixel);
int main(){
int size = 0;
cout << "Enter image size: ";
cin >> size;
int ** pixel = new int *[size + 2];
for (int i = 1; i <= size; i++)
{
pixel[i] = new int[size + 2];
}
cout << "Enter the pixel array in row-major order:\n";
for (int i = 1; i <= size; i++)
for (int j = 1; j <= size; j++)
{
cin >> pixel[i][j];
}
labelComponents(size, pixel);
outputImage(size, pixel);
system("pause");
return (0);
}
void labelComponents(int size, int **pixel){
// initialize offsets
Position * offset = new Position[4];
offset[0] = Position(0, 1); // right
offset[1] = Position(1, 0); // down
offset[2] = Position(0, -1); // left
offset[3] = Position(-1, 0); // up
int numNbr = 4; // neighbors of a pixel position
Position * nbr = new Position(0, 0);
Position * Q = new Position[size * size];
int id = 1; // component id
int x = 0; // (Position Q)
// scan all pixels labeling components
for (int r = 1; r <= size; r++) // row r of image
for (int c = 1; c <= size; c++) // column c of image
{
if (pixel[r][c] == 1)
{// new component
pixel[r][c] = ++id; // get next id
Position * here = new Position(r, c);
do
{// find rest of component
for (int i = 0; i < numNbr; i++)
{// check all neighbors of here
nbr->setRow(here->getRow() + offset[i].getRow());
nbr->setCol(here->getCol() + offset[i].getCol());
if (pixel[nbr->getRow()][nbr->getCol()] == 1)
{// pixel is part of current component
pixel[nbr->getRow()][nbr->getCol()] = id;
Q[x] = *nbr;
x++;
}
}
// any unexplored pixels in component?
*here = Q[x]; // a component pixel
x--;
} while (here != NULL);
} // end of if, for c, and for r
}
} // end of labelComponents
void outputImage(int size, int **pixel){
cout << "The labeled image is: ";
for (int i = 1; i <= size; i++){
cout << endl;
for (int j = 1; j <= size; j++)
cout << pixel[i][j] << " ";
}
} // end of outputImage
//Position.h
#ifndef POSITION_H
#define POSITION_H
class Position
{
private:
int row; // row number of the position
int col;
// column number of the position
public:
Position(); // default
Position( int theRow, int theCol); // parameter
Position(const Position & aPosition); // copy
Position & operator = (const Position & aPosition); // overload =
// overload =
// mutators
void setRow (int r);
void setCol (int c);
//accessors
int getRow() const;
int getCol() const;
}; // end Position
Position::Position()
{
setRow(0);
setCol(0);
}
Position::Position(int r, int c)
{
setRow(r);
setCol(c);
}
Position::Position(const Position & aPosition)
{
setRow(aPosition.row);
setCol(aPosition.col);
}
Position & Position::operator=(const Position & aPosition)
{
this->row=aPosition.row;
this->col=aPosition.col;
return(*this);
}
void Position::setRow(int r)
{
this->row = r;
}
void Position::setCol(int c)
{
this->col = c;
}
int Position::getRow() const
{
return this->row;
}
int Position::getCol() const
{
return this->col;
}
#endif
In C/C++, arraw indexes go from 0 to n-1, not from 1 to n. All your for loops are wrong:
for (int i = 1; i <= size; i++)
Must be replaced by:
for (int i = 0; i < size; i++)
Else, you access array at sizeposition which is out of bound.
Using a debugger and/or working with smaller piece of code would have made it easier for you to figure this out ;-)
I have this code. From main function i twice call sportPrisevinners function and if it is first call of this function it works correctly and I recive correct result, but when i call it second time I recive incorrect result even I pass this function with same arguments. Please help me to solve this problem while it doesn`t make me crasy.
const char* countries[] = {"ru", "gb", "us", "uk", "ch", "de"};
const int countriesCount = 6;
const char* sports[] = {"runing", "swiming", "baseball", "football", "jumping", "kerling"};
const int sportsCount = 6;
enum {
Empty = 0,
Bronse,
Silver,
Gold
};
struct member {
char sport[9];
char country[3];
int points;
int medal;
};
struct members {
member* list;
int count;
};
string medalToStr(int medal)
{
switch (medal) {
case Gold:
return "Gold";
case Silver:
return "Silver";
case Bronse:
return "Bronse";
default:
return "Empty";
}
}
void printMembers(members &list)
{
for (int i = 0; i < list.count ; i++)
cout << /*i << " " <<*/ medalToStr(list.list[i].medal) << " in "
<< list.list[i].sport << " with " << list.list[i].points
<< " from " << list.list[i].country << endl;
}
void generate()
{
ofstream file("members.dat", ios::binary|ios::trunc);
member temp;
for (int i = 0; i < sportsCount ; i++)
for (int j = 0; j < countriesCount ; j++)
{
int count = rand()%5+5;
for (int k = 0; k < count ; k++)
{
strcpy(&temp.sport[0], sports[i]);
strcpy(&temp.country[0], countries[j]);
temp.points = rand()%100;
temp.medal = Empty;
file.write((char*)&temp, sizeof(member));
}
}
file.close();
}
members sportPrisevinners(const char* sport)
{
//reading
ifstream file("members.dat", ios::binary);
member* loaded = new member[60];
int pos = 0;
while (!file.eof())
{
member temp;
file.read((char*)&temp, sizeof(member));
static bool reading = false;
if (strncmp(&temp.sport[0], sport, strlen(sport))==0) {
reading = true;
loaded[pos++] = temp;
} else if (reading) {
break;
}
}
file.close();
//sorting
int count = 3;
for (int i = 0; i < pos-1 ; i++)
{
for (int j = i+1; j < pos ; j++)
if (loaded[i].points<loaded[j].points)
{
member temp = loaded[i];
loaded[i] = loaded[j];
loaded[j] = temp;
}
if (i<count) {
static int last = -1;
if (loaded[i].points==last)
count++;
loaded[i].medal = count-i;
last = loaded[i].points;
} else break;
}
//returning
members result;
result.list = new member[count];
memcpy(result.list, loaded, count*sizeof(member));
/*for (int i = 0; i < count; i++)
result.list[i] = loaded[i];*/
result.count = count;
delete[] loaded;
return result;
}
int main(int /*argc*/, char */*argv*/[])
{
srand(time(0));
generate();
members r = sportPrisevinners(sports[4]);
printMembers(r);
delete[] r.list;
members l = sportPrisevinners(sports[5]);
printMembers(l);
delete[] l.list;
system("pause");
return 0;
}
I suspect it's the static local variables in your function. They won't have the same values on each call to the function, and this could affect the results. The initialization of these variables is performed just once - the first time they come into scope - so each subsequent time the function is called, you pick up the values these variables had last time the function ran.