Vector will not print after reading from file - c++

I am trying to print my vector in the display function, but it fails. I'm about 80% sure my syntax is correct. I have tried passing it from class to class. I am sure the file is being read in correctly because when I put my for loop in ClientProcessing() it works fine but I want to separate them.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
// struct to hold the initial information of each client
struct Clients
{
string client_name = " "; // first and last as one line
char account_type = ' '; // C for Checking - S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
};
// Prototype for Account Manager
class AccManager
{
public:
vector<Clients> client_info;
string client_name = ""; // first and last as one line
char account_type = ' '; // C for Checking / S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
AccManager(){};
void set_name(string n) {client_name = n;};
string get_name(){return client_name;};
void set_type(char t){account_type = t;};
char get_type(){return account_type;};
void set_initial_deposit(double d){initial_deposit = d;};
double get_initial_deposit(){return initial_deposit;};
};
// Prototype for the UI - User interface
class UI
{
public:
void ClientProcessing();
void ShowClientInfo();
};
int main()
{
UI ui;
ui.ClientProcessing();
ui.ShowClientInfo();
}
// A module that reads in the the client data file
void UI::ClientProcessing()
{
ifstream infile;
AccManager a;
int i = 0;
cout << "Processing client information...\n";
infile.open("client_data.txt");
if(infile.is_open()){
cout << "Opened client file sucessfully! \n";
while(!infile.eof()){
while (i < 1){
getline(infile, a.client_name, '\t');
a.set_name(a.client_name);
a.client_info.push_back(Clients());
a.client_info[i].client_name = a.get_name();
i++;
}
}
}
else{
cout << "Error opening file! \n";
}
infile.close();
}
// A module to display the client info as a table
void UI::ShowClientInfo()
{
AccManager a;
cout << "Name D\n";
for(int i = 0; i < a.client_info.size(); i++){
cout << a.client_info[i].client_name; // Will not print here
}
}

Converted my code to the following and passed in the vector. It worked!
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
// struct to hold the initial information of each client
struct Clients
{
string client_name = " "; // first and last as one line
char account_type = ' '; // C for Checking - S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
};
// Prototype for Account Manager
class AccManager
{
public:
vector<Clients> client_info;
string client_name = ""; // first and last as one line
char account_type = ' '; // C for Checking / S for savings;
double initial_deposit = 0.0; // Amount for initial deposit
AccManager(){};
void set_name(string n) {client_name = n;};
string get_name(){return client_name;};
void set_type(char t){account_type = t;};
char get_type(){return account_type;};
void set_initial_deposit(double d){initial_deposit = d;};
double get_initial_deposit(){return initial_deposit;};
};
// Prototype for the UI - User interface
class UI
{
public:
void ClientProcessing(vector<Clients> &client_info);
void ShowClientInfo(vector<Clients> client_info);
};
int main()
{
UI ui;
AccManager a;
ui.ClientProcessing(a.client_info);
ui.ShowClientInfo(a.client_info);
}
// A module that reads in the the client data file
void UI::ClientProcessing(vector<Clients> &client_info)
{ AccManager a;
ifstream infile;
int i = 0;
cout << "Processing client information...\n";
infile.open("client_data.txt");
if(infile.is_open()){
cout << "Opened client file sucessfully! \n";
while(!infile.eof()){
while (i < 1){
getline(infile, a.client_name, '\t');
a.set_name(a.client_name);
client_info.push_back(Clients());
client_info[i].client_name = a.get_name();
i++;
}
}
}
else{
cout << "Error opening file! \n";
}
infile.close();
}
// A module to display the client info as a table
void UI::ShowClientInfo(vector<Clients> client_info)
{
cout << "Name D\n";
for(int i = 0; i < client_info.size(); i++){
cout << client_info[i].client_name;
}
}

Related

Unable to assign a range sub-string to an array of strings. c++

So I'm unable to create a substring cut using ranges. I am making an airport program where you feed the program a txt.file and it has to divide the lines I get from it into different strings. For instance, I have the following text data:
CL903 LONDON 41000 14.35 08906 //number of flight, destination, price, etc.
UQ5723 SYDNEY 53090 23.20 12986
IC5984 TORONTO 18030 04.45 03260
AM608 TOKYO 41070 18.45 11315
so the first string will be on the lines of this (variables are in Spanish):
numVuelo[n] = M[n].substr(0,5)
this line will work perfectly, but when I move to the next one (from 7 to 14), it tells me that it's out of range, even though It's between the 0 and 31st values of the length of the string.
M[n] gets all of the strings on the text, I'm using Codeblocks and a class style with header and all. I'll copy the code below...
This is my header Vuelo.h:
#ifndef VUELO_H
#define VUELO_H
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
class Vuelo
{
public:
Vuelo(int N);
virtual ~Vuelo();
void setM();
void setNumVuelo(string _numVuelo, int n);
void setDestino(string _destino, int n);
void setPrecio(string _precio, int n);
private:
string M[NUM_FLIGHTS];
string numVuelo[NUM_FLIGHTS];
string destino[NUM_FLIGHTS+1]; //somehow "destino" doesn't work without the +1 but everything else does
float precio[NUM_FLIGHTS];
Then, on another code called Vuelo.cpp I have the following
#include "Vuelo.h"
Vuelo::Vuelo(int N)
{
M[N] = { };
numVuelo[N] = { };
destino[N] = { };
precio[N] = { };
}
Vuelo::~Vuelo()
{
//nope
}
void Vuelo::setM()
{
int c = 1;
string s;
ifstream F ("flights.txt");
if(F.is_open())
{
while (!F.eof())
{
getline(F,s);
M[c] = s;
cout << M[c] << endl;
c++;
}
//sets all values
for(c = 0; c < NUM_FLIGHTS; c++)
{
setNumVuelo(M[c],c);
setDestino(M[c],c);
setPrecio(M[c],c);
}
F.close();
}
else
{
cout << "ERROR document wasn't found" << endl;
}
}
void Vuelo::setNumVuelo(string _numVuelo, int n)
{
numVuelo[n]= _numVuelo.substr(0,5); //this works
cout << numVuelo[n] <<endl;
}
void Vuelo::setDestino(string _destino, int n)
{
destino[n] = _destino.substr(7, 13); //PROBLEM HERE
cout << destino[n] << " " << destino[n].length() << endl;
}
void Vuelo::setPrecio(string _precio, int n)
{
string p = _precio.substr(15,19); //PROBLEM HERE
precio[n] = atof(p.c_str());
cout << precio[n] <<endl;
}
And finally my main looks like this:
#include "Vuelo.h"
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
int main()
{
cout << "Bienvenido, reserva tu vuelo!" << endl;
cout << "-----------------------------------" << endl;
Vuelo* flight = new Vuelo(NUM_FLIGHTS);
flight->setM();
return 0;
}
Thanks :)

Cannot locate segmentation fault. Allocating memory in constructor?

I've been at this for hours, but I can't seem to locate where the core dump is coming from. I've limited it down to the main constructor and a couple functions but I cant find where the error is coming from. Any help would be appreciated.
destructor
Vehicle:: ~Vehicle(){
delete [] name;
}
base header
#ifndef VEHICLE_H
#define VEHICLE_H
#include <iostream>
#include <string>
using namespace std;
class Vehicle{
protected:
char *name;
static ostream *out ;
public:
Vehicle();
Vehicle(string &n);
Vehicle (const Vehicle & b);
~Vehicle();
Vehicle& operator =(const Vehicle &b);
virtual void print(void) = 0;
virtual void read(void) = 0;
};
#endif // VEHICLE_H
Constructor in base implementation
Vehicle :: Vehicle(){
name = new char[1];
strcpy(name[0], "");
}
Vehicle :: Vehicle(string &n){
int len = n.length()+ 1;
name = new char[len];
strcpy(name,n.c_str());
}
Vehicle :: Vehicle(const Vehicle & v){
int len = strlen(v.name)+ 1;
name = new char[len];
strcpy(name,v.name);
}
Header for inherited class
#ifndef MOTORVEHICLE_H
#define MOTORVEHICLE_H
#include <cstring>
#include "vehicle.h"
class MotorVehicle: public Vehicle{
protected:
string make;
string model;
double mpg;
public:
MotorVehicle();
MotorVehicle (const string &n,const string &m = "",const string &md = "", const double &mp = 0.0);
//accessor functions
string getName()const;
string getMake()const;
string getModel()const;
double getMpg()const;
ostream & getOut();
//mutator functions
string setName();
void setMake();
void setModel();
void setMpg();
void setOut(ostream & o);
//virtual functions
void print();
void read();
};
#endif // MOTORVEHICLE_H
Inherited class.
#include "motorVehicle.h"
#include <string>
#include <iostream>
MotorVehicle:: MotorVehicle(): Vehicle(), make(""), model(""), mpg(0.0){
make = "";
model = "";
mpg = 0.0;
}
MotorVehicle :: MotorVehicle(const string &n, const string &m, const string &md, const double &mp){
int len = n.length()+ 1;
delete [] name;
name = new char[len];
strcpy(name,n.c_str());
make = m;
model = md;
mpg = mp;
}
//accessor functions
string MotorVehicle :: getName()const{
string temp(name);
return temp;
}
string MotorVehicle :: getMake()const {
return make;
}
string MotorVehicle :: getModel()const {
return model;
}
double MotorVehicle :: getMpg()const {
return mpg;
}
ostream & MotorVehicle :: getOut(){
return *out;
}
//mutator functions
string MotorVehicle :: setName(){
cerr << "dododd" <<endl;
string nm1;
cin >> nm1;
int len = nm1.length()+ 1;
delete [] name;
name = new char[len];
strcpy(name,nm1.c_str());
}
void MotorVehicle :: setMake(){
cin >> make;
}
void MotorVehicle :: setModel(){
cin >> model;
}
void MotorVehicle :: setMpg(){
cin >> mpg;
}
void MotorVehicle :: setOut(ostream & o){
out = &o;
}
//virtual function
void MotorVehicle :: print(){
*out << name << make << model << mpg <<" ";
}
void MotorVehicle :: read(){
*out << "Please enter name for this Vehicle: " << endl;
setName();
*out << "Please enter make for this Vehicle: " << endl;
setMake();
*out << "Please enter model for this Vehicle: " << endl;
setModel();
*out << "Please enter miles per gallon for this Vehicle: " << endl;
setMpg();
}
Main
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include "motorVehicle.h"
// car.h & truck.h included twice to test #ifndef #define ... #endif structure
#include "car.h"
#include "car.h"
#include "truck.h"
#include "truck.h"
typedef vector<MotorVehicle *> vectorOfMotorVehicle;
using namespace std;
// prompt the user for the Vehicle type to create, and get the reply
string prompt(void);
int main() {
vectorOfMotorVehicle v; // store dynamically created MotorVehicles
// or objects derived from MotorVehicles
int numVehicles = 0; // denotes how many MotorVehicles we have
string reply; // indicates type of MotorVehicle to build
bool error = false; // set when a user response is in error
string outputLocation; // where the output of print() will go
ofstream *out = NULL;
MotorVehicle *m;
// uncomment following line to test that Vehicle is an abstract base class
// Vehicle theVehicle;
// push a Vehicle into the vector so first "real" Vehicle is at position 1
m = new MotorVehicle("None");
v.push_back(m);
// chose where the output will go
cout << "Where would you like the output? ";
cin >> outputLocation;
if (outputLocation == "stdout") {
; // no action to take, because stdout (i.e., cout) is the default
} else if (outputLocation == "stderr") {
v[0]->setOut(cerr);
} else {
out = new ofstream;
out->open(outputLocation.c_str());
if (out->fail()) {
cerr << "Error: error writing to " << outputLocation << endl;
return 1;
}
v[0]->setOut(*out);
}
// get the type of Vehicle to create
reply = prompt();
// loop, reading vehicle descriptions, until a "quit" command is received
while (reply != "quit") {
// create the new MotorVehicle object and push it into the vector
switch (toupper(reply[0])) {
case 'T' : m = (MotorVehicle *) (new Truck);
v.push_back(m);
break;
case 'C' : m = (MotorVehicle *) (new Car);
v.push_back(m);
break;
case 'Q' : reply = "quit";
continue;
default : cerr << "Incorrect response\n\n";
error = true;
}
// if no error, then we have a new Vehicle to initialize via read()
if (!error) {
numVehicles++;
v[numVehicles]->read();
}
// reset error flag, and request a new Vehicle type
error = false;
reply = prompt();
}
// report on what Vehicles were created to test read() and print()
for (int i = 0; i <= numVehicles; i++) {
//*out << "Vehicle " << i << endl;
// print the Vehicle characteristics (attributes)
v[i]->print();
//*out << endl;
// free the storage for this Vehicle
delete v[i];
}
// if we opened an output file, then close it
if (out != NULL) {
out->close();
delete out;
}
return 0;
}
// prompt the user for the Vehicle type to create, and get the reply
string prompt() {
string reply; // the user reponse to the prompt
// prompt for and get user response
cout << "\nWhich type of vehicle would you like to initialize"
<< "\n--car or truck (or \"quit\" to exit): ";
cin >> reply;
return reply;
}
I tried to narrow it down as much as possible, but the other two inherited classes follow a similar inheritance so I omitted it. Any help would be hugely appreciated. Thanks again

Iterate over array of objects from txt file

I have file with records separated by comas:
cities.txt:
1,NYC
2,ABQ
...
I would like to iterate over each row: ids and names. I have created the code:
#include <iostream>
#include <string>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, int name)
{
this->id = id;
this->name = name;
}
void load_file()
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
while (!v_file.eof()) {
//...
}
}
v_file.close();
}
}
int main()
{
City array_city[1000];
array_city.load_file();
return 0;
}
Could you tell me how to load all rows to array array_city and iterate over it? I don't know what to place in while block in load_file method. I don't know weather, the method load_file should have void type. Unfortunately I have to do it on arrays.
It's not a good idea to use EOF in a while loop. Read more in Why is iostream::eof inside a loop condition considered wrong?
In c++, vectors should be preferred over arrays. However, your teacher knows something more to suggest using an array here. For that reason I am providing a solution with an array:
Read the file line by line
Extract the id and the string
Assign it to the i-th cell of the array
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, string name) : id(id), name(name)
{
}
void print()
{
cout << "ID = " << id << ", name = " << name << endl;
}
};
void load_file(City* cities, const int n)
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
int number, i = 0;
string str;
char c;
while (v_file >> number >> c >> str && c == ',' && i < n)
{
//cout << number << " " << str << endl;
cities[i++] = {number, str};
}
}
v_file.close();
}
int main()
{
City cities[4]; // assuming there are 4 cities in the file
load_file(cities, 4);
for(unsigned int i = 0; i < 4; ++i)
cities[i].print();
return 0;
}
Same solution with std::vector, if you are interested. =) If you haven't been taught about them, I suggest you skip that part and come back later when you do that in the course.
Use a vector of City. Read the file line by line, and push back into the vector every line you read, by constructing an instance of your class, and you are done!
Example:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, string name) : id(id), name(name)
{
}
void print()
{
cout << "ID = " << id << ", name = " << name << endl;
}
};
void load_file(vector<City>& cities)
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
int number;
string str;
char c;
while (v_file >> number >> c >> str && c == ',' && i < n)
{
//cout << number << " " << str << endl;
cities.push_back({number, str});
}
}
v_file.close();
}
int main()
{
vector<City> cities;
load_file(cities);
for(unsigned int i = 0; i < cities.size(); ++i)
cities[i].print();
return 0;
}
Input:
Georgioss-MacBook-Pro:~ gsamaras$ cat cities.txt
1,NYC
2,ABQ
3,CCC
4,DDD
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++0x main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
ID = 1, name = NYC
ID = 2, name = ABQ
ID = 3, name = CCC
ID = 4, name = DDD

Compiler telling me I am not correctly using the this pointer

Here is a picture of the error:
I have created a basic class that would hold the information of a sports team. When I am attempting to compare two teams with each other with the this pointer, I am receiving an error. Here are my two files. Hopefully, it is just a simple error.
Team.cpp
#include "Team.h"
#include <string>
#include <sstream>
using namespace std;
Team::Team()
{
teamName = "The Strings";
winNum = 0;
lossNum = 0;
numPlayers = 11;
points = 0;
}
Team::Team(const char newName, int newPlayers)
{
stringstream move;
string strName;
move << newName;
move >> strName;
teamName = strName;
numPlayers = newPlayers;
}
void Team::display() // displays information about the team.
{
cout << "Team name:" << teamName << endl;
cout << "This team has " << numPlayers << " players" << endl;
cout << "This team has " << winNum << " wins and " << lossNum << endl;
}
void Team::addWins() // increment the number of wins
{
winNum = winNum + 1;
}
void Team::addLosses() // increment the number of losses.
{
lossNum = lossNum + 1;
}
void Team::addPlayer(int nrPlayers)
{
numPlayers = numPlayers + nrPlayers;
}
void Team::delPlayers(int nrPlayers)
{
numPlayers = numPlayers - nrPlayers;
}
void Team::setTeam(char name[], int players, int wins, int losses)
{
string strname(name);
teamName = name;
numPlayers = players;
winNum = wins;
lossNum = losses;
}
bool isBetter(const Team &other)
{
if (this->points > other.points)
{
return true;
}
else
{
return false;
}
}
int Team::getWins() // returns the number of wins for a team object
{
return winNum;
}
int Team::getLosses() // returns the number of losses for a team object
{
return lossNum;
}
int Team::getPoints() // returns the number of points a team has
{
points = winNum - lossNum;
return points;
}
Team.h
#ifndef TEAM_H
#define TEAM_H
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
// definition of class Dice
class Team
{
private:
int numPlayers,
winNum,
lossNum;
int points;
string teamName ;
public:
// default constructor: initializes the face of a new
// Dice object to 1
Team();
Team(const char newName, int newPlayers);
void display(); // displays information about the team.
void addWins(); // increment the number of wins
void addLosses(); // increment the number of losses.
void addPlayer(int nrPlayers);
void delPlayers(int nrPlayers);
void setTeam(char name[], int players, int wins, int losses);
bool isBetter(const Team &other);
int getWins(); // returns the number of wins for a team object
int getLosses(); // returns the number of losses for a team object
int getPoints(); // returns the number of points a team has
};
#endif

C++ Alphabetical Insertion Sort

We are doing a project involving storing and comparing various cities. We have become stuck after adding a new city into the database, it goes to the bottom of the list - we want it to go into the database, sorted alphabetically. As only one value can be added at a time, all the other entries will already be alphabetical.
Below is the relevant code to this.
The problem area is the // Insertion Sort when adding // out bit.
The error codes are:
[BCC32 Error] File1.cpp(250): E2294 Structure required on left side of . or .*
[BCC32 Error] File1.cpp(250): E2108 Improper use of typedef 'node'
[BCC32 Error] File1.cpp(250): E2188 Expression syntax
All corresponding to the line
while (strcmp(cityTemp.fname, node[l]) < 0) && (l <= ct )
If you could point us in the right direction, that would be great. Thanks
// -------------------------------------------------------------------------- //
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include <iomanip>
#define PI 3.14159265
using namespace std;
// -------------------------------------------------------------------------- //
class node
{
private:
char city[100];
char country[100];
float longitudeDegree;
float longitudeMinutes;
char eastWest[2];
float latitudeDegree;
float latitudeMinutes;
char northSouth[2];
//useful for link list!
node *next;
// -------------------------------------------------------------------------- //
public:
//Constructor for class node
// ctn = city node
// cyn = country node
// longD = longitude degree
// longM = longitude minutes
// ew = east / west
// latD = latitude distance
// latM = latitude minutes
// ns = north / south
node(char ctn[], char cyn[], float longD,
float longM, char ew[], float latD, float latM, char ns[])
{
//Copy char array ctn to class array city
//string copy is part of string header
strcpy(city, ctn); //copy to string city name
strcpy(country, cyn); //copy to string country name
longitudeDegree = longD;
longitudeMinutes = longM;
strcpy(eastWest, ew);
latitudeDegree = latD;
latitudeMinutes = latM;
strcpy(northSouth, ns);
cout << "Hello from node with name: " << city << endl;
}
// -------------------------------------------------------------------------- //
// Get function to return city stored in class //
char* getCity()
{
return city;
}
char* getCountry()
{
return country;
}
float getLongDe()
{
return longitudeDegree;
}
float getLongMin()
{
return longitudeMinutes;
}
char* getEastWest()
{
return eastWest;
}
float getLatDe()
{
return latitudeDegree;
}
float getLatMin()
{
return latitudeMinutes;
}
char* getNorthSouth()
{
return northSouth;
}
};
// -------------------------------------------------------------------------- //
class menu
{
private:
int fnum, mnum, ct, xx, fg, ans, ans2;
float longitudeDegree;
float longitudeMinutes;
float latitudeDegree;
float latitudeMinutes;
char country[100];
char eastWest[2];
char northSouth[2];
//array of pointers of type class node
node *db[200]; //denotes how many pointers to use for the amount of cities in database
char fname[200];
char pt[200];
char sfnum[200];
char yn[2]; //yes/no
public:
//constructor
menu()
{
//Read the serialized data file
ct= Readit();
}
// -------------------------------------------------------------------------- //
void start()
{
// Add a city //
case 1:
cout << "Enter the name of the city:";
cin.getline(fname,100);
fg=Findit(ct,fname);
if(fg>0)
{
cout << "This entry is already in the database: " << fname <<endl;
}
else
{
cout << "Enter the Country of " << fname << endl;
cin >> country;
//ans2 = '-1';
do
{
cout << "Enter the Longitude Degrees (0 - 180) of " << fname <<endl ;
cout << "Enter degrees between 0 - 180 \n";
cin >> ans2;
}
while(!((ans2 >=0)&&(ans2 <=180)));
longitudeDegree = ans2;
//ans2 = '-1';
do
{
cout << "Enter the Longitude Minutes (0 - 60) of " << fname << endl;
cout << "Enter minutes between 0 - 60 \n";
cin >> ans2;
}
while(!((ans2 >=0)&&(ans2 <=60)));
longitudeMinutes = ans2;
ans = 'Z'; //default to an answer not in while loop
do
{
cout << "East or West?\n";
cout << "You must type a capital 'E' or a capital 'W'.\n";
cin >> ans;
}
while((ans !='E')&&(ans !='W'));
eastWest[0] = ans;
eastWest[1] = '\0';
//ans2 = '-1';
do
{
cout << "Enter the Latitude Degree (0 - 90) of " << fname << endl;
cout << "Enter degrees between 0 - 90 \n";
cin >> ans2;
}
while(!((ans2 >=0)&&(ans2 <=180)));
latitudeDegree = ans2;
//ans2 = '-1';
do
{
cout << "Enter the Latitude Minutes (0 - 60) of " << fname << endl;
cout << "Enter minutes between 0 - 60 \n";
cin >> ans2;
}
while(!((ans2 >=0)&&(ans2 <=60)));
latitudeMinutes = ans2;
ans = 'Z'; //default to an answer not in while loop
do
{
cout << "North or South?\n";
cout << "You must type a capital 'N' or a capital 'S'.\n";
cin >> ans;
}
while((ans !='N')&&(ans !='S'));
northSouth[0] = ans;
northSouth[1] = '\0';
ct++;
db[ct]=new node(fname,country,longitudeDegree,longitudeMinutes,
eastWest,latitudeDegree,latitudeMinutes,northSouth);
/* // Insertion Sort when adding //
node *cityTemp;
cityTemp=db[ct];
//cityTemp = new node (fname, country, longitudeDegree, longitudeMinutes, eastWest, latitudeDegree, latitudeMinutes, northSouth);
int j, l;
// Find place to insert the new city //
// All other cities will already be in alphabetical order
l=0;
while (strcmp(cityTemp.fname, node[l]) < 0) && (l <= ct )
//strcmp(cityTemp.fname, node[l].fname)<0) && (l<=ct)
{
l++;
}
// Move down rest
for (j = l, j <= ct);
{
j++;
}
db[j+1] = db[j];
db[j] = cityTemp; */
}
break;
}
// -------------------------------------------------------------------------- //
// Function to convert string to lower case ascii //
char *strLower( char *str )
{
char *temp;
for ( temp = str; *temp; temp++ )
{
*temp = tolower( *temp );
}
return str;
}
// -------------------------------------------------------------------------- //
// Function to search through the names stored in nodes //
int Findit(int ctt,char fnamef[])
{
int nn=0;
int xx;
for(int k=1;k<=ctt;k++)
{
xx=strcmp(strLower(db[k]->getCity()),strLower(fnamef));
//xx is zero if names are the same
if(xx==0)
nn=k;
}
return nn;
}
// -------------------------------------------------------------------------- //
// Function to do serialization of nodes and store in a file //
void Storeit(int ctt)
{
fstream outfile;
outfile.open("cityList.txt",ios::out);
outfile<<ctt<<endl;
for(int k=1;k<=ctt;k++)
{
//outfile<<db[k]->getName()<<endl;
outfile<<db[k]->getCity()<<endl;
outfile<<db[k]->getCountry()<<endl;
outfile<<db[k]->getLongDe()<<endl;
outfile<<db[k]->getLongMin()<<endl;
outfile<<db[k]->getEastWest()<<endl;
outfile<<db[k]->getLatDe()<<endl;
outfile<<db[k]->getLatMin()<<endl;
outfile<<db[k]->getNorthSouth()<<endl;
}
outfile.close();
}
// -------------------------------------------------------------------------- //
int Readit()
// Function to open the file, read in the data and create the nodes
{
int ctx=0;
fstream infile;
infile.open("cityList.txt",ios::in);
//infile>>ctx;
infile.getline(sfnum,200);
ctx=atoi(sfnum);
/*
for(int k=1;k<=ctx;k++)
{
//infile>>fname;
infile.getline(fname,200);
//infile>>weight;
infile.getline(sfnum,200);
weight=atof(sfnum);
//infile>>height;
infile.getline(sfnum,200);
height=atof(sfnum);
db[k]=new node(fname,height,weight);
}
*/
// Read in file to variables i.e. longitudeDegree = atof(sfnum)
for(int k=1;k<=ctx;k++)
{
//infile>>fname;
infile.getline(fname,100);
//infile>>country ;
infile.getline(sfnum,100);
strcpy(country,sfnum);
//infile>>longitudeDegree;
infile.getline(sfnum,100);
longitudeDegree=atof(sfnum);
//infile>>longitudeMinutes;
infile.getline(sfnum,100);
longitudeMinutes=atof(sfnum);
//infile>>eastWest ;
infile.getline(sfnum,100);
strcpy(eastWest,sfnum);
//infile>>latitudeDegree;
infile.getline(sfnum,100);
latitudeDegree=atof(sfnum);
//infile>>latitudeMinutes;
infile.getline(sfnum,100);
latitudeMinutes=atof(sfnum);
//infile>>northSouth ;
infile.getline(sfnum,100);
strcpy(northSouth,sfnum);
db[k]=new node(fname,country, longitudeDegree,
longitudeMinutes, eastWest, latitudeDegree, latitudeMinutes, northSouth);
}
infile.close();
return ctx;
}
};
// End of class menu
Don't you mean to use db[l] - the variable - rather than node - the type.
Azorath wrote:
(strcmp(cityTemp.fname, node[i]) < 0) && (l <= ct )
and after some give and take we've got, with some confusion between i, I and l....
(strcmp(cityTemp.fname, db[i]->getcity()) < 0) && (l??? <= ct )
yes? (how does Erik know that db[i] is in the code?)
I'm taking a guess that cityTemp is an instance of node, not a pointer to node, and that db[] is an array of pointers to nodes, yes?
One thing wrong is "cityTemp.fname" - there is no "fname" member in the class. Its looking for a structure containing a member "fname". Do you mean cityTemp.city?
Try that and trport what you get...