Repeat a print out value of the last data .

Pages: 12
Thank you and I was really wondering why it was just giving me the same result then using time as a seed gave me a way out and also the boundaries did do the trick...

The code seems to be running well when I am using the above main as testing but when I link it to my Questions application it gives me some errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
    ifstream ifs("example.txt");
    if (!ifs)
        return (cout << "Cannot open file\n"), 1;

    vector<Quiz> quizzes;
    LoadQuestions(ifs,quizzes);
    Vector<Quiz> myQuiz(quizzes);
    myQuiz.shuffle();
    for (int i = 0; i < myQuiz.size(); ++i) {
        std::cout<<myQuiz.get(i); //Here I have the hope of geting the quizzes attributes
    }
   return 0;
}
Last edited on
Greetings again, I have created a struct with intention of making it read files and display the high score, and to store the highest top 5 players throughout the lifetime of the game.

I have struct A certain template Class to sort But the issue is the Template seems to not respond and gives error or it prints nothing not sure what could be the error in that case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
//
// Created by Sithe on 6/2/2021.
//
#include <iostream>
#include <string>
#include <fstream>
#include "HighScore.h"
#include <string>
#include "SortClass.h"
//Used to Print the 5 users with Highest Score
SortClass<HighScore> HighScoreSort;
void  HighScore::print_score(std::ifstream& file) {
    std::string players;
    while (getline(file, players)) {
        std::cout << players;
    }
}
void HighScore::addFirst(HighScore *high_scores, std::string name, std::string lastname, int score){
    high_scores[0].Name=name;
    high_scores[0].LastName=lastname;
    high_scores[0].Score=score;
    std::cout<<score;
}

//This makes the error when using the template;
void HighScore::addNewHighScore( HighScore *high_scores, std::string name, std::string lastname, int score) {
    int size = sizeof(high_scores) / sizeof(high_scores[0]);
    if(size<5){
        high_scores[size].addNewHighScore(high_scores, name, lastname, score);
    }
    for (int i = 0; i < 5; ++i) {
        if(high_scores[i].rank>rank){
            HighScoreSort.sort(high_scores, 5);
            high_scores[0].addNewHighScore(high_scores, name, lastname, score);
        }
    }
}

void HighScore::writeToFile(HighScore *high_scores){
    std::ofstream outputFile;
    outputFile.open("users.txt", std::ios::app);
    int size = sizeof(high_scores) / sizeof(high_scores[0]);
    for (int i = 0; i <size; ++i) {
        outputFile <<(i+1)<< high_scores->Name << " " << high_scores->LastName << " " <<high_scores->Score  <<std::endl;
    }
}

int main(){
    HighScore e;
    HighScore *high_scores;
    std::string Name, LastName;
    int Score;
    std::cout << "Enter the Firt Name : ";
    std::cin >> Name;
    std::cout << "Enter the Last Name : ";
    std::cin >> LastName;
    std::cout << "Enter the rank : ";
    std::cin >> Score;
    e.addFirst(high_scores, Name, LastName, Score);
    std::cout<<"Hey";
    int size = sizeof(high_scores) / sizeof(high_scores[0]);
    std::cout<<size;
    e.writeToFile(high_scores);
    std::ifstream ifs("user.txt");;
    if (!ifs)
        return (std::cout << "Cannot open file\n"), 1;

    e.print_score(ifs);

}


#include <string>
//
// Created by Sithe on 6/2/2021.
//

#ifndef COMP315FINALPROJECT_HIGHSCORE_H
#define COMP315FINALPROJECT_HIGHSCORE_H

struct HighScore {
public:
    std::string Name;
    std::string LastName;
    double Score;
    int rank;

    void writeToFile(HighScore *highScore);
    void addNewHighScore(HighScore *high_scores, std::string, std::string, int);
    void addFirst(HighScore *high_scores, std::string name, std::string, int score);
    void print_score(std::ifstream& f);
};

#endif //COMP315FINALPROJECT_HIGHSCORE_H


//
// Created by Sithe on 6/2/2021.
//

#include "SortClass.h"
template <class T>
void sort(T arr[], int SIZE){
    for (int i = 0; i < SIZE; i++)
    {
        for (int j = i+1; j < SIZE; j++)
        {
            if (arr[i] > arr[j])
            {
                T temp;
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}


//
// Created by Sithe on 6/2/2021.
//

#ifndef COMP315FINALPROJECT_SORTCLASS_H
#define COMP315FINALPROJECT_SORTCLASS_H

template<typename T>
class SortClass {
public:javascript:editbox1.editSend()
    void sort(T arr[], int SIZE);
};


#endif //COMP315FINALPROJECT_SORTCLASS_H 
No idea what you mean by "the template", but on line 27 and line 42 sizeof(high_scores) isn't going to work. high_scores is just passed as a pointer; it has no knowledge of the array size in the calling routine.

BTW this appears to be a completely different problem to the rest of the thread, which will cause confusion.
Last edited on
I still get similar error as of mine at the beginning


This compiles and runs OK with VS2019:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstdlib>
#include <ctime>

template <typename ValueType>
class Vector {
public:
	Vector();
	Vector(const std::vector<ValueType>& list);
	~Vector() { delete[] elements; }

	// To be provided if needed
	Vector(const Vector&) = delete;
	Vector& operator=(const Vector&) = delete;

	explicit Vector(size_t n, ValueType value = ValueType());
	void checkIndex(size_t index, size_t min, size_t max, const std::string& prefix) const;
	void shuffle();
	size_t size() const { return count; }
	const ValueType& get(size_t index) const;

private:
	ValueType* elements {};
	size_t capacity {};
	size_t count {};
};

template <typename ValueType>
Vector<ValueType>::Vector() { }

template<typename ValueType>
Vector<ValueType>::Vector(size_t n, ValueType value) : capacity(n), count(n), elements(new ValueType[n]) {
	std::fill_n(elements, n, value);
}

template <typename ValueType>
void Vector<ValueType>::shuffle() {
	for (size_t i = 0; i < count; ++i)
		if (const auto j {std::rand() % count}; i != j)
			std::swap(elements[i], elements[j]);
}

template <typename ValueType>
const ValueType& Vector<ValueType>::get(size_t index) const {
	checkIndex(index, 0, count - 1, "get");
	return elements[index];
}

template <typename ValueType>
void Vector<ValueType>::checkIndex(size_t index, size_t min, size_t max, const std::string& prefix) const {
	if (index < min || index > max) {
		std::ostringstream out;

		out << "Vector::" << prefix << ": index of " << index << " is outside of valid range ";
		if (size() < 1)
			out << " (empty vector)";
		else {
			out << "[";

			if (min < max)
				out << min << ".." << max;
			else if (min == max)
				out << min;

			out << "]";
		}

		std::cout << " !Error! " << out.str() << '\n';
	}
}

template <typename ValueType>
Vector<ValueType>::Vector(const std::vector<ValueType>& v) : count(v.size()), capacity(v.capacity()), elements(new ValueType[v.size()]) {
	std::copy_n(v.begin(), count, elements);
}

template <typename T>
void shuffle(Vector<T>& v) {
	v.shuffle();
}

int main() {
	srand(static_cast<unsigned>(time(nullptr)));

	const std::vector<std::string> my {"A", "B", "C", "D"};
	Vector<std::string> v(my);

	v.shuffle();

	std::cout << v.size() << ' ';
	std::cout << v.get(3) << ' ';
	std::cout << v.get(2) << '\n';

	//Trying to shuffle the above String
	for (int i = 0; i < my.size(); ++i)
		std::cout << v.get(i) << '\n';
}

For the highest scores, perhaps something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>

constexpr size_t maxScores {5};

struct Score {
	std::string name;
	std::string lastName;
	double score {};
};

class HighScore {
public:
	void writeToFile(std::ofstream&);
	void addScore(const std::string&, const std::string&, double);
	void print_scores();
	void readFromFile(std::ifstream&);

private:
	std::vector<Score> scores;
};

void HighScore::print_scores() {
	for (size_t rnk {1}; const auto & [name, lastName, score] : scores)
		if (rnk <= maxScores)
			std::cout << rnk++ << "  " << name << ' ' << lastName << "  " << score << '\n';
}

void HighScore::addScore(const std::string& name, const std::string& lastname, double score) {
	scores.emplace_back(name, lastname, score);

	std::sort(scores.begin(), scores.end(), [](const auto& lhs, const auto& rhs) {return lhs.score > rhs.score; });
}

void HighScore::writeToFile(std::ofstream& ofs) {

	for (size_t i = 0; i < std::min<size_t>(scores.size(), maxScores); ++i)
		ofs << scores[i].name << ' ' << scores[i].lastName << ' ' << scores[i].score << '\n';
}

void HighScore::readFromFile(std::ifstream& ifs)
{
	size_t rnk {1};

	for (Score sc; rnk++ <= maxScores && ifs >> sc.name >> sc.lastName >> sc.score; scores.emplace_back(sc));
}

int main() {
	constexpr const char* const fnam {"users.txt"};

	std::ifstream ifs(fnam);

	if (!ifs)
		return (std::cout << "Cannot open file\n"), 1;

	HighScore e;

	e.readFromFile(ifs);

	std::string Name, LastName;
	int Score {};

	std::cout << "Enter the First Name : ";
	std::cin >> Name;

	std::cout << "Enter the Last Name : ";
	std::cin >> LastName;

	std::cout << "Enter the score : ";
	std::cin >> Score;

	e.addScore(Name, LastName, Score);

	ifs.close();

	std::ofstream ofs(fnam);

	if (!ofs)
		return (std::cout << "Cannot open file\n"), 2;

	e.writeToFile(ofs);
	e.print_scores();
}

Thanks @seeplus
Vector<Quiz> myQuiz;

Your code runs well on the Vector template when using general datatypes but upon using those as I have created it returns an error of
1
2
3
4
5
6
 

Vector<std::string> myQuiz; //Works very well
Vector<Quiz> myQuiz; //This one returns an error not sure why
 

CMakeFiles\Comp315FinalProject.dir/objects.a(PractiseStream.cpp.obj): In function `main':

undefined reference to `Vector<Quiz>::Vector()'
collect2.exe: error: ld returned 1 exit status




On the code of struct is similar project just not linked yet, I tried creating a struct to sort the the score before I print them to the file
Probably because Quiz doesn't have the required member functions - such as copy constructor, operator=, default constructor etc.
@seeplus I really first believe that was the case but the Template has everything but now it seems like not working well when it is use in another class which is the Quiz Class. As meaning when I put the #include "Quiz.h" on the Vector template class and use the quiz it does work there and gives me no syntax error.

But I am more kin of using it in the Quiz class rather than in the Vector Template as More of the action takes place there.

In case I take the loadQuestions and add it to the Vector class.
Here is the method in the vector template class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  ifstream ifs("example.txt");
    if (!ifs)
        return (cout << "Cannot open file\n"), 1;

    vector<Quiz> quizzes;
    Quiz qu;
    qu.LoadQuestions(ifs,quizzes);
    std::cout<<quizzes.size();
    Vector<Quiz> myQuiz(quizzes);
    std::cout<<myQuiz.size();

    myQuiz.shuffle();
    for (int i = 0; i < myQuiz.size(); ++i) {
        std::cout<<myQuiz.get(i);
    }


While output is which can be sorted
But my biggest question now why is not responsive can it be a better way to import the class or perhaps use the Vector with something like that of std::


Pick the other name of operator function.
MCQ
easy
3
function overloading
operator overloading
member overloading
object overloading

Pick out the other definition of objects.
MCQ
average
3
member of the class
associate of the class
attribute of the class
instance of the class

Which of the following accesses a variable in structure *b?
MCQ
average
0
b->var;
b.var;
b-var;
b>var;



And tried look into your method but gave me some error and to advance that I can fix it (Write and Print on HighScore struct)
Last edited on
Topic archived. No new replies allowed.
Pages: 12