Searching through a vector.
Scanning a CSV file for a word, return it's entire line.
I've been working on a a program to create and manage CSV data structures. The struggle is real. I'd come up with a few reasonable functions, such as, creating a new record, reading out the entire file (with break points), reading out a particular record by reference number, editing or deleting particular records, and finally, search capabilities.
Working on a way to find a particular word I could use to bring up a record, so far, I've come up with this function. Although not perfect yet, it does return the last mention of the word in the data structure. I would prefer it could bring up ALL mentions of the word, but I have not managed to get that far yet.
Let me know in the comments, what you think I should do to, say perhaps, list all records with Sacramento as the city listed.
Here are the two working functions. The first finds the word, the second prints out the record.
bool FindString(std::string filename, std::string searchstring)
{
char a;
int recordnumber = 0;
cout << "\n";
fstream file;
vector<string> lines;
string line, value, newvalue, substring;
int count;
int i;
file.open(filename, ios:: in |ios::out | ios::app);
if(!file.is_open())
{
cout << "No such file. ERR:105.ur\n";
return false;
}
else
{
while(getline(file, line))
{
lines.push_back(line);
count = lines.size();
if(lines.empty())
{
cout << Colors::SetColoredText(Colors::Bold, Colors::Red, Colors::Black, " File is empty.\n");
return false;
}
for(i = 0; i < count; i++)
{
if(i < count)
{
value = searchstring;// = value;
size_t pos = line.find(value);
if(pos != std::string::npos)
{
size_t nextpos = line.find(",", pos);
int itcount = nextpos - pos;
recordnumber = i;
}
}
}
}
}
ReadItemAt(filename, recordnumber);
return true;
}
//--------------------------------------------------------------------------
bool ReadItemAt(std::string filename, int recordnumber)
{
if(recordnumber == 0)
{
return false;
}
cout << "\n";
fstream file;
vector<string> lines;
string line, value, newvalue, substring;
int index;
int count;
file.open(filename, ios:: in |ios::out | ios::app);
if(!file.is_open())
{
cout << "No such file. ERR:105.ria\n";
return false;
}
else
{
int i;
while(getline(file, line))
{
lines.push_back(line);
count = lines.size();
}
if(lines.empty())
{
cout << Colors::SetColoredText(Colors::Bold, Colors::Red, Colors::Black, " File is empty.\n");
return false;
}
for(i = 0; i < count; i++)
{
if(i == recordnumber)
{
cout << "Records in file : " << count << "\n";
cout << "Record No -> " << to_string(i) << " -> " << lines[i] << "\n";
}
}
}
return true;
}

No comments:
Post a Comment