I have a text file that I need to search records in. The records are saved line by line in this format ID NAME SCORE1 SCORE2 SCORE3 .... They are all separated by a tab space. What I am trying to do is to print the line that has been found as
ID : 123
NAME: asdhasj
SCORE1: 123
What I need to achieve is to store the results that have been found into an array and then format the data in the way I want it to be printed but I am not able to. Here is a part of my code so far, this just prints out the data segment by segment.
#include <iostream>
#include <fstream>
#include <string>
#include <vector> // We will use this to store Players
struct Player // Define a "Player" data structure
{
int ID;
std::string Name;
int Score1, Score2, Score3;
};
std::istream& operator>>(std::istream& is, Player& p)
{
// In this function we will define how information is inputted into the player struct
// std::cin is derived from the istream class
is >> p.ID >> p.Name >> p.Score1 >> p.Score2 >> p.Score3;
// When we have extracted all of our information, return the stream
return is;
}
std::ostream& operator<<(std::ostream& os, Player& p)
{
// Just like the istream, we define how a player struct is displayed when using std::cout
os << "ID: " << p.ID << "\nName: " << p.Name << "\nScore1: " << p.Score1 << "\nScore2: " << p.Score2 << "\nScore3: " << p.Score3 << "\n";
// When we have extracted all of our information, return the stream
return os;
}
////////////////////////////////////////////////////////////////////////////////////////////
void Load(std::vector<Player>& r, std::string filename) // Taken from my latest code
{
std::ifstream ifs(filename.c_str()); // Open the file name
if(ifs)
{
while(ifs.good()) // While contents are left to be extracted
{
Player temp;
ifs >> temp; // Extract record into a temp object
r.push_back(temp); // Copy it to the record database
}
std::cout << "Read " << r.size() << " records.\n\n";
}
else
{
std::cout << "Could not open file.\n\n";
}
}
void Read(std::vector<Player>& r) // Read record contents
{
for(unsignedint i = 0; i < r.size(); i++)
std::cout << r[i] << "\n";
}
void Search(std::vector<Player>& r, std::string n) // Search records for name
{
std::cout << "Searching records for " << n << "\n\n";
for(unsignedint i = 0; i < r.size(); i++)
{
if(r[i].Name.find(n) != std::string::npos)
std::cout << r[i];
}
}
int main()
{
std::vector<Player> records;
Load(records, "players.txt");
Read(records);
Search(records, "misheck");
return 0;
}
players.txt:
01 Titan 10 20 30
02 misheck 30 50 80
OUTPUT:
Read 2 records.
ID: 1
Name: Titan
Score1: 10
Score2: 20
Score3: 30
ID: 2
Name: misheck
Score1: 30
Score2: 50
Score3: 80
Searching records for misheck
ID: 2
Name: misheck
Score1: 30
Score2: 50
Score3: 80
[Finished in 0.5s]
Please do not hesitate if you are stuck or struggling to understand something, I am more than happy to help.