Invalid static_cast from struct to char* - c++

I am trying to do a uni assignment (first year), where the task is to read in a file filled with records (in this case fake student records), insert them into a struct array in the code, write that struct array to a .dat file, and then read the file back in and verify it.
I keep getting an error about converting my struct to a char* (line 155)
Please don't be too technical with the answer, as I have only been coding for a few months ahah
/*
* File: lab3.cpp
* Author: tom
*
* Created on August 19, 2015, 12:02 AM
*/
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
//Structure declaration area
struct marks // A structure for user data
{
int studentnumber;
float ass1;
float ass2;
float ass3;
float ass4;
int labs;
float exam;
float total;
};
//Function Prototyping
void structinsert(ifstream&);
void binarywrite(ofstream&);
int binaryread(ifstream& , marks);
//Global Array for student marks
marks students [100];
int main(int argc, char* argv[])
{
ifstream fin;
ofstream fout;
int recordsread = 0;
fin.open(argv[1]); //Input file opened from cmdline args
fout.open(argv[2]); // Output file opened from cmdline args
if (fin.fail())
{
cerr << "Input file not found. Terminating..." << endl;
}
else if (fout.fail())
{
cerr << "Output file not found. Terminating..." << endl;
}
else
{
structinsert(fin);//Function which places data into the global "student" array
binarywrite(fout);
fin.close();
fout.close();
fin.open(argv[2]);
int cnt = 0;
while((!fin.eof()) && (cnt < 100))
{
fin.read(static_cast<char *>(&students[cnt]), sizeof(marks));
cnt++;
}
cout << "Records Read: " << recordsread << endl;
}
return 0;
}
void structinsert(ifstream& input)
{
float temp;
float value;
// Ignore first line of headings
input.ignore(150, '\n');
for (int x = 0; x < 100; x++)
{
input >> students[x].studentnumber;
input.ignore (1);
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass1 = 0;
}
else
{
input >> students[x].ass1;
input.ignore(1,'\t');
}
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass2 = 0;
}
else
{
input >> students[x].ass2;
input.ignore(1,'\t');
}
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass3 = 0;
}
else
{
input >> students[x].ass3;
input.ignore(1,'\t');
}
temp = input.peek();
if (temp == '\t')
{
input.ignore(1,'\t');
students[x].ass4= 0;
}
else
{
input >> students[x].ass4;
input.ignore(1,'\t');
}
input >> students[x].labs;
input.ignore(1,'\t');
temp = input.peek();
if (temp == '\n')
{
input.ignore(1,'\t');
students[x].exam = 0;
}
else
{
input >> students[x].exam;
input.ignore(1,'\t');
}
}
}
void binarywrite(ofstream& output)
{
output.write(reinterpret_cast<char*>(&students),100*sizeof(marks));
}

Related

Why do I get a segmentation fault when fetching this variable?

I am pulling names as strings from a file, create a Person *p object, and put it into an array.
Then to search the array for a name but when I try to fetch the name I get a segmentation fault.
Why is this segmentation fault happening, and what can I do to fix it?
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string firstName;
string lastName;
string phoneNumber;
public:
Person();
Person(string f, string l, string n);
~Person(void);
void setName()
{
}
string getFirstName()
{
return firstName;
}
string getLastName()
{
return lastName;
}
string getNumber() { return phoneNumber; }
void print();
};
Array creation.
{
ifstream file;
file.open("phonebook.txt");
if (!file.is_open()) //Check for File Error.
{
cerr << "Failed to open file" << endl;
exit(1);
}
//Get Array Size
string line;
while (getline(file, line))
{
count++;
}
file.close();
//Create an array
Person *arrList[count];
buildArray(arrList, count);
if (uInput == "a" || uInput == "A") //To add
{
int x = addPerson();
if (x == 1)
{
count++;
}
delete[] arrList;
}
void buildArray(Person *arr[], int size)
{
string f, l, n;
ifstream file;
file.open("phonebook.txt");
for (int i = 0; i < size; i++)
{
file >> f >> l >> n;
Person *p = new Person(f, l, n);
arr[i] = p;
delete p;
}
}
The search, This is the part that has the trouble. I have tried a few different things including creating 2 Persons, and comparing their parts but whenever it goes into the .h it can not return the name.
if (uInput == "s" || uInput == "S")
{ //To Search
string f, l;
cout << "Find Who (Firstname Lastname) " << endl;
cin >> f >> l;
Person *n = new Person(f, l, "");
int i = 0;
bool found = false;
while (i <= count && found == false)
{
Person *p = new Person("", "", "");
p = arrList[i];
if (p->getFirstName() == n->getFirstName() && p->getLastName() == n->getLastName())
{
arrList[i]->print();
found = true;
delete p;
delete n;
}
i++;
}
while (i == count && found == false)
{
cout << "No results found. " << endl;
found = true;
}
}

Invalid address specified to RtlValidateHeap( 00E90000, 00E9FBC8 ) Project.exe has triggered a breakpoint

I am getting this error while running the program . Does anyone have any idea what is the problem here ?
HEAP[Project3.exe]: Invalid address specified to RtlValidateHeap( 00E90000, 00E9FBC8 )
Project3.exe has triggered a breakpoint.
HERE IS ALL THE CODE (Updated) . Do you think is dome memory problem or IDE problem?
#include <iostream>
#include <fstream>
#include "HeapSort.h"
using namespace std;
int main(int argc, char* argv[]) {
// Input/OutPut files.
string fileInput = argv[1];
string fileOutput1 = argv[2];
string fileOutput2 = argv[3];
ofstream ofs;
//This for loop is used to clear the output files before writting to them.
for (int i = 2; i <= 3; i++){ ofs.open(argv[i], std::ofstream::out | std::ofstream::trunc); ofs.close(); }
//Initializing HeapSort class
HeapSort HS(fileInput, fileOutput1, fileOutput2);
HS.buildHeap();
HS.deleteHeap();
system("PAUSE");
return 0;
}
//HeapSort.h file.
#ifndef HeapSort_H
#define HeapSort_H
#include <iostream>
#include <fstream>
using namespace std;
class HeapSort {
public:
int* heapAry;
int numItems, rootIndex, fatherIndex, leftKidIndex, rightKidIndex, minKidIndex, data;
string input, output1, output2;
//constructor
HeapSort(string filename1, string filename2, string filename3);
int countData();
void buildHeap();
void deleteHeap();
int getRoot();
void replaceRoot();
void bubbleUp(int s);
void bubbleDown(int fatherIndex);
bool isLeaf(int index);
bool isRoot(int index);
int findMinKidIndex(int fatherIndex);
bool isHeapEmpty();
bool isHeapFull();
void printHeap(int s);
void inserOneDataItem(int data);
};//end of HeapSort class
#endif
//HeapSort.cpp file.
#include "HeapSort.h"
#include <iostream>
#include <fstream>
#include<string>
#include <sstream>
#include <algorithm>
using namespace std;
//Used for int conversion to string since library is broken.
namespace patch{
template < typename T > std::string to_string(const T& n){
std::ostringstream stm;
stm << n;
return stm.str();
}
}//End of patch namespace.
//Constructor
HeapSort::HeapSort(string filename1, string filename2, string filename3){
data = countData() + 1;
heapAry = new int[data];
for (int i = 0; i <= data; i++){ heapAry[i] = 0; }
input = filename1;
output1 = filename2;
output2 = filename3;
}//End of cunstructor
int HeapSort::countData(){
ifstream inFile;
inFile.open(input);
int tempInt = 0;
int counter = 0;
while (inFile >> tempInt) { cout << tempInt << "\n"; counter++; }//end of while loop
inFile.close();
return counter;
}//End of countData function
void HeapSort::buildHeap(){
ifstream inFile;
inFile.open(input);
int number = 0;
rootIndex = 1;
while (inFile >> number) {
inserOneDataItem(number);
int kidIndex = heapAry[0];
bubbleUp(kidIndex);
printHeap(1);
}//end of while loop
inFile.close();
}//End of buildHeap function
void HeapSort::deleteHeap(){
ofstream outFile;
outFile.open(output2, ios::app);
while (isHeapEmpty() != true){
int data = getRoot();
if (data != 0){ outFile << " | " << data << " | \n"; }
replaceRoot();
fatherIndex = rootIndex;
bubbleDown(fatherIndex);
printHeap(2);
}//end of while loop
outFile.close();
}//End of deleteHeap function.
int HeapSort::getRoot(){
return heapAry[1];
}//End of getRoot function
void HeapSort::replaceRoot(){
heapAry[1] = heapAry[heapAry[0]];
heapAry[0] = heapAry[0] - 1;
}//End of replaceRoot function
void HeapSort::bubbleUp(int s){
if (isRoot(s)){ return; }//end if clause
else{
fatherIndex = s / 2;
if (heapAry[s] >= heapAry[fatherIndex]){
return;
}//end inner if clause
else{
int temp = heapAry[s];
heapAry[s] = heapAry[fatherIndex];
heapAry[fatherIndex] = temp;
bubbleUp(fatherIndex);
}//end inner else clause
}//end outter else clause
}//End of bubbleUp function
void HeapSort::bubbleDown(int fatherIndex){
if (isLeaf(fatherIndex)){ return; }//end if clause
else{
leftKidIndex = fatherIndex * 2;
rightKidIndex = (fatherIndex * 2) + 1;
minKidIndex = findMinKidIndex(fatherIndex);
if (heapAry[minKidIndex] >= heapAry[fatherIndex]){ return; }//end inner if clause
else{
int temp = heapAry[fatherIndex];
heapAry[fatherIndex] = heapAry[minKidIndex];
heapAry[minKidIndex] = temp;
bubbleDown(minKidIndex);
}//end inner else clause
}//end outter else clause
}//End of bubbleDown function
bool HeapSort::isLeaf(int index){
if (index * 2 > heapAry[0] && (index * 2) + 1 > heapAry[0]){ return true; }//end if clause
else { return false; }//end else clause
}//End of isLeaf function
bool HeapSort::isRoot(int index){
return (index == 1);
}//End of isRoot function
int HeapSort::findMinKidIndex(int fatherIndex){
if (isLeaf(fatherIndex) == true) return fatherIndex;
if ((fatherIndex * 2) + 1 > heapAry[0] && heapAry[(fatherIndex * 2)] < fatherIndex) return fatherIndex * 2;
if ((fatherIndex * 2) + 1 < fatherIndex && (fatherIndex * 2) == 0) return (fatherIndex * 2) + 1;
else{
int s = std::min(heapAry[fatherIndex * 2], heapAry[(fatherIndex * 2) + 1]);
if (s == heapAry[fatherIndex * 2]){ return fatherIndex * 2; }
else { return (fatherIndex * 2) + 1; }
}//end outer else clause
}//End of findMinKidIndex function
bool HeapSort::isHeapEmpty(){ return (heapAry[0] == 0); }//end of isHeapEmpty method
bool HeapSort::isHeapFull(){ return (numItems == data); }//end of isHeapFull method
void HeapSort::printHeap(int s){
ofstream outFile;
outFile.open(output1, ios::app);
if (s == 1){ outFile << "Printing heap after adding one element! \n\n"; }
else if (s == 2){ outFile << "Printing heap after removing one element! \n\n"; }
for (int i = 0; i <= heapAry[0]; i++){
if (heapAry[i] != 0){ outFile << heapAry[i] << " | "; }//end if clause
}//end for loop
outFile << "\n\n\n";
// outFile.close();
}//end of printHeap
void HeapSort::inserOneDataItem(int data){
heapAry[0]++;
heapAry[heapAry[0]] = data;
}//end of inserOneDataItem method
I did not go through your code fully but I have doubt on the below code.
data = countData() + 1;
heapAry = new int[data];
for (int i = 0; i <= data; i++){ heapAry[i] = 0; }
For an example you are allocating 10 data into the heapAry(0-9) statement and
initializing(0-10) the 11 data to the same variable.
Can you please check the below loop (0-10).
for (int i = 0; i <= data; i++){ heapAry[i] = 0; }
Thanks,
Manivasakan B.
Actually the whole problem was that the input on countData function was never initialized when called , thats way that function would return a 0 value and cause that error . Solved by the owner .....

Error with strcoll (C++)

I want to sort a vector of strings into order alphabetically. I have coded thus far and I can not resolve the error for strcoll. Also, I am not allowed to use algorithm library. The error can be seen in the bubbub function where I am trying to bubble sort.
I have a few functions that should explain themselves with their names
#include <iostream>
#include <string.h>
#include <vector>
#include <stdio.h>
using namespace std;
inline void swap(string & a, string & b)
{
string c = b;
b = a;
a = c;
return;
}
void input_name(string&);
void sort_names(string&);
void repeat_pro(int&);
void sortArray(string, int);
void print_names(vector<string>& b_list);
void bubbub(vector<string> & b_list);
int main() {
vector<string> b_list;
string name;
int choice;
int count=0;
cout << "Welcome to the Business Sorting Program!" << endl;
do{
input_name(name);
b_list.push_back(name);
count++;
repeat_pro(choice);
bubbub(b_list);
cout<<"\n \n Your Businesses are:"<<endl;
for(int i=0; i < b_list.size() ; i++){
cout<<b_list[i]<<"\n";
}
cout << "\n\n";
}while(choice == 0);
cout << "Thanks for using this program"<<endl;
return 0;
}
void input_name(string &name){
cout << "Enter in the name of the business: ";
getline(cin, name);
}
void sort_names(string &name){
}
void repeat_pro(int &choice){
cout << "Do you want to enter in more names: ";
string answ;
cin>>answ;
cin.ignore(1000,'\n');
for (int x=0; x<answ.size(); x++){
answ[x] = tolower(answ[x]);
}
if (answ == "yes" || answ == "y"){
choice = 0;
}
else {
choice = 1;
}
}
void bubbub(vector<string> & b_list)
{
vector<string>::size_type loop = 0;
bool done = false;
while ((loop+1 < b_list.size()) && ! done)
{
done = true;
for (vector<string>::size_type count = 0;
count+1 != b_list.size(); count++)
{
string x;
string z;
x = b_list[count];
z= b_list[count+1];
if ( strcoll (x,z) < 0 )
{
swap( b_list[count], b_list[count+1] ); // swap
done = false;
}
}
loop++;
}
return;
}
I fixed it by converting my string into a list of chars. then compared them and swapped the vector based on the results. Thanks for the help guys
void bubbub(vector<string> & b_list)
{
vector<string>::size_type loop = 0;
bool done = false;
while ((loop+1 < b_list.size()) && ! done)
{
done = true;
for (vector<string>::size_type count = 0;
count+1 != b_list.size(); count++)
{
string x;
string z;
char array[50];
char array2[50];
x = b_list[count];
z= b_list[count+1];
strncpy(array, x.c_str(), sizeof(x));
strncpy(array2, z.c_str(), sizeof(z));
if ( strcoll (array,array2) > 0 )
{
swap(b_list[count+1], b_list[count] ); // swap
done = false;
}
}
loop++;
}
return;
}
You can use std::string::compare instead of strcoll
#include <iostream>
#include <vector>
#include <stdio.h>
#include <cstring>
using namespace std;
inline void swap(string & a, string & b)
{
string c = b;
b = a;
a = c;
return;
}
void input_name(string&);
void sort_names(string&);
void repeat_pro(int&);
void sortArray(string, int);
void print_names(vector<string>& b_list);
void bubbub(vector<string> & b_list);
int main() {
vector<string> b_list;
string name;
int choice;
int count=0;
cout << "Welcome to the Business Sorting Program!" << endl;
do{
input_name(name);
b_list.push_back(name);
count++;
repeat_pro(choice);
bubbub(b_list);
cout<<"\n \n Your Businesses are:"<<endl;
for(int i=0; i < b_list.size() ; i++){
cout<<b_list[i]<<"\n";
}
cout << "\n\n";
}while(choice == 0);
cout << "Thanks for using this program"<<endl;
return 0;
}
void input_name(string &name){
cout << "Enter in the name of the business: ";
getline(cin, name);
}
void sort_names(string &name){
}
void repeat_pro(int &choice){
cout << "Do you want to enter in more names: ";
string answ;
cin>>answ;
cin.ignore(1000,'\n');
for (int x=0; x<answ.size(); x++){
answ[x] = tolower(answ[x]);
}
if (answ == "yes" || answ == "y"){
choice = 0;
}
else {
choice = 1;
}
}
void bubbub(vector<string> & b_list)
{
vector<string>::size_type loop = 0;
bool done = false;
while ((loop+1 < b_list.size()) && ! done)
{
done = true;
for (vector<string>::size_type count = 0;
count+1 != b_list.size(); count++)
{
string x;
string z;
x = b_list[count];
z = b_list[count+1];
if (z.compare(x) != 0 )
{
swap( b_list[count], b_list[count+1] ); // swap
done = false;
}
}
loop++;
}
return;
}
Output
Welcome to the Business Sorting Program!
Enter in the name of the business: hello
Do you want to enter in more names: yes
Your Businesses are:
hello
Enter in the name of the business: apple
Do you want to enter in more names: no
Your Businesses are:
apple
hello
Thanks for using this program
Program ended with exit code: 0

(C++) terminate called after throwing an instance of 'std::bad_alloc'

I keep getting an error of bad memory allocation. I've spent the whole night trying to find where I went wrong but I can't figure out what.
I've combed through every line but still nothing. Could it be that my program/laptop just isn't strong enough?
Any help would be extremely helpful. My head is ringing and I need some rest.
Here's my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
// struct to store word + count combinations
struct wordItem{
string word;
int count;
};
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords);
bool isCommonWord(string word, vector<string>& _vecIgnoreWords);
void printTopN(wordItem wordItemList[], int topN);
void doubleArray(wordItem wordItemList[], int size);
int getTotalNumberNonCommonWords(wordItem wordItemList[], int size, int wordCount);
const int STOPWORD_LIST_SIZE = 50;
// ./a.out 10 HW1-HungerGames_edit.txt HW1-ignoreWords.txt
int main(int argc, char* argv[]){
vector<string> vecIgnoreWords(STOPWORD_LIST_SIZE);
// verify we have the correct # of parameters, else throw error msg & return
if (argc != 4){
cout << "Usage: ";
cout << argv[0] << " <number of words> <filename.txt> <ignorefilename.txt>"<< endl;
return 0;
}
//Set vector with stop words
getStopWords(argv[3], vecIgnoreWords);
//initialize struct array
int aSize = 100;
wordItem *theStructArray = new wordItem[aSize];
int counter = 0;
int doubleCount = 0;
//read main txt file
ifstream inFile(argv[1]);
if(inFile.is_open()){
string line;
string theWord;
//extract words from file
while(getline(inFile, line)){
istringstream iss(line);
//extract and analyze word
while(iss >> theWord){
if(!(isCommonWord(theWord, vecIgnoreWords))){
bool inStructArray = false;
int inStructPosition;
//search for word in Struct array
while (inStructArray == false){
for(int i=0; i<aSize; i++){
if (theWord == theStructArray[i].word){
inStructArray = true;
inStructPosition = i;
}
}
break;
}
//if word is in struct array
if (inStructArray == true){
theStructArray[inStructPosition].count++;
}
//else if it isn't
else{
//create new wordItem and add into struct
wordItem newWord;
newWord.word = theWord;
newWord.count = 1;
theStructArray[counter+(100*doubleCount)] = newWord;
counter++;
}
//if struct array hits maximum amount of elements,
if (counter == (aSize-1)){
doubleArray(theStructArray, aSize);
counter = 0;
doubleCount++;
aSize +=100;
}
}
}
}
inFile.close();
}
//Bubble sort masterArray
int bI, bJ, flag = 1;
wordItem bTemp;
for(bI=1; (bI <= aSize && flag); bI++){
flag = 0;
for(bJ=0; bJ<aSize; bJ++){
if(theStructArray[bJ+1].count > theStructArray[bJ].count){
bTemp = theStructArray[bJ];
theStructArray[bJ] = theStructArray[bJ+1];
theStructArray[bJ+1] = bTemp;
flag = 1;
}
}
}
//Print topN words
printTopN(theStructArray, atoi(argv[1]));
//print others
cout << "#" << endl;
cout << "Array doubled: " << doubleCount << endl;
cout <<"#" << endl;
cout << "Unique non-common words: "<< (aSize-100+counter)<<endl;
cout << "#"<<endl;
cout <<"Total non-common words: "<< getTotalNumberNonCommonWords(theStructArray, aSize, counter)<<endl;
return 0;
}
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords){
ifstream inFile(ignoreWordFileName);
if(inFile.is_open()){
int a = 0;
string line;
while(getline(inFile, line)){
_vecIgnoreWords.insert(_vecIgnoreWords.begin() + a, line);
}
inFile.close();
}
return;
}
bool isCommonWord(string word, vector<string>& _vecIgnoreWords){
for(int i=0; i<STOPWORD_LIST_SIZE; i++){
if(word == _vecIgnoreWords.at(i)){
return true;
}
}
return false;
}
void printTopN(wordItem wordItemList[], int topN){
cout << endl;
for(int i=0; i<topN; i++){
cout<< wordItemList[i].count << '-' << wordItemList[i].word << endl;
}
return;
}
void doubleArray(wordItem wordItemList[], int size){
wordItem *tempArray = new wordItem[size+100];
for(int i=0; i<size; i++){
tempArray[i] = wordItemList[i];
}
delete [] wordItemList;
wordItemList = tempArray;
}
int getTotalNumberNonCommonWords(wordItem wordItemList[], int size, int wordCount){
int total = 0;
for(int i=0; i<(size-100+wordCount); i++){
total+=wordItemList[i].count;
}
return total;
}
You are doing very bad things in void doubleArray(wordItem wordItemList[], int size)
you can call delete [] on the array if you pass an array, but you cannot change its value, so doubleArray(theStructArray, aSize); will cause theStructArray to be deleted but not assigned to the memory you allocated. You are just assigning the local variable in the function doubleArray
It is similar to:
void doubleit(int x)
{
x *= 2;
}
int y=3;
doubleit(y);
here x was momentarily doubled to 6, but y never changed.
you need to use references, or better make theStructArray a std::vector and be done with it.

Calling a base function from derived class function?

The class BaseSearch is the base function that I'm trying to call within the derived function (ValueSearch).
The code that I have in question specifically is under ValueSearch, calling BaseSearch::Print(line, title). The compiler errors I'm getting are:
I'm uncertain if I'm using inheritance correctly.
Error 1 error C2275: 'std::string' : illegal use of this type as an expression
BaseSearch.cpp
BaseSearch::BaseSearch()
{
}
BaseSearch::~BaseSearch()
{
}
void Print(string line, string title)
{
char c2 = '_'; //set character to blank value; defines the header row
char c = '_'; //set character to blank value; defines the searched row
int numHeader = 0; //sets the value of character for the header row
int numLine = 0; //sets the value of character for the searched row
c2 = line[numLine];
while (true) //force while loop
{
c = title[numHeader]; numHeader++; //header character is set to the title array defined as the entire header string above
if (c != ',')
{
cout << c; // couts the header until it reaches a ','
}
if (c == ',' || title.size() == numHeader) // if c reaches a ',' it will print the searched row
{
cout << ": ";
while (line.size() != numLine)
{
while (c2 != ',' && line.size() != numLine)
{
cout << line[numLine];
numLine++;
if (line.size() != numLine)
c2 = line[numLine];
else
break;
}
if (line.size() != numLine)
{
numLine++;
c2 = line[numLine];
cout << "\n";
break;
}
}
}
if (title.size() == numHeader) // if c reaches a null value, it breaks until other row is found.
{
cout << endl << endl; break;
}
}
}
BaseSearch.h
#ifndef BASESEARCH_H
#define BASESEARCH_H
#include <string>
class BaseSearch
{
public:
BaseSearch();
virtual ~BaseSearch();
virtual void Print(string, string);
};
Value Search.cpp
ValueSearch::ValueSearch()
{
string input;
}
ValueSearch::~ValueSearch()
{
//dtor
}
double ValueSearch::getInput()
{
cout << endl << "Enter the name of the company you would like to search for: ";
cin >> input;
return input;
}
void ValueSearch::ValueSearchFunc(int c, int x)
{
column = c;
// cout << "Enter the name of the company you would like to search for: ";
// getline(cin, input);
string line;
ifstream fs("Stock Database.csv");
string title;
getline(fs, title);
while (!fs.eof())
{
getline(fs, line);
string companyname = ""; //start as blank, then append
string a;
int commacount = 0; //how many commas have we passed
int ChrCount = 0; //counter for which character in the line we are looking at
while (line != "\0") //while the line does not equal to null value.
{
double price;
price = 0;
a = line[ChrCount]; //convert char c to a string (a) so that we can append
ChrCount++;
if (a == ",")
{
commacount++; //increases the comma count as a encounters a comma each time.
}
else if (commacount == column && (a != "N" && a != "/" && a != "A")) //if comma count is equal to the set column, it will append the string company name.
{
while (a != ",")
{
if (a != ",")
{
companyname.append(a);
a = line[ChrCount];
ChrCount++;
}
}ChrCount--;
price = stod(companyname);
}
else if (commacount > column) // if the comma count is any value larger than the column, breaks out of loop.
{
break;
}
if (input == 0)
{
break;
}
if (x == 1){
if (price >= input && price != 0) // if the appended company name is equal to the search input entered, it will cout the entire row.
BaseSearch::Print(line, title);
}
if (x == 2)
{
if (price <= input && price != 0) // if the appended company name is equal to the search input entered, it will cout the entire row.
BaseSearch::Print(line, title);
}//end if
}
}
}
ValueSearch.h
#ifndef VALUESEARCH_H
#define VALUESEARCH_H
#include <string>
#include "BaseSearch.h"
class ValueSearch : public BaseSearch
{
public:
ValueSearch();
~ValueSearch();
double getInput();
void ValueSearchFunc(int c, int x);
void Print(string,string) {BaseSearch::Print(string,string);}
protected:
private:
double input;
int column;
};
#endif
It seems you are a beginner of C++.I will show you an example code which will compile successfully.
BaseSearc.h:
#ifndef BASESEARCH_H
#define BASESEARCH_H
#include <string>
using namespace std;
class BaseSearch
{
public:
BaseSearch();
~BaseSearch();
void Print(string, string);
};
#endif
BaseSearch.cpp:
#include "BaseSearch.h"
#include <iostream>
BaseSearch::BaseSearch()
{
}
BaseSearch::~BaseSearch()
{
}
void BaseSearch::Print(string line, string title)
{
cout << "line:" << line << endl;
cout << "title:" << title << endl;
}
ValueSearch.h:
#ifndef VALUESEARCH_H
#define VALUESEARCH_H
#include <string>
#include "BaseSearch.h"
class ValueSearch : public BaseSearch
{
public:
ValueSearch();
~ValueSearch();
double getInput();
void ValueSearchFunc(int c, int x);
protected:
private:
double input;
int column;
};
#endif
ValueSearch.cpp:
#include "ValueSearch.h"
ValueSearch::ValueSearch()
{
}
ValueSearch::~ValueSearch()
{
}
double ValueSearch::getInput()
{
return input;
}
void ValueSearch::ValueSearchFunc(int c, int x)
{
//where is 'input' from?
//if (x == 1)
//{
// if (price >= input && price != 0)
// BaseSearch::Print(line, title);
//}
//if (x == 2)
//{
// if (price <= input && price != 0)
// BaseSearch::Print(line, title);
//}//end if
}
But I've no idea what ValueSearchFunc wants to do.
There is no realization of BaseSearch constructor/destructor in code. And Print function realization should be
void BaseSearch::Print(string line, string title)
{
//code
}