i have been provided middleearth.h/cpp and was asked to make a makefile, doxyfile (which i did correctly) and a topological.cpp that works but has a small mistake in the output and i need help with that please.ill provide all three files and the text we use to test and the error.
cs2110 cs2150
cs2102 cs2150
cs1110 cs2110
cs3330 cs4414
cs2150 cs4414
cs2110 cs3330
cs1110 cs2102
0 0
middleearth.h
#ifndef MIDDLEEARTH_H
#define MIDDLEEARTH_H
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <random>
using namespace std;
// see the comments in the lab11 write-up, or in middleearth.cpp
class MiddleEarth {
public:
MiddleEarth(int xsize, int ysize, int num_cities, int seed);
void print();
void printTable();
float getDistance(const string& city1, const string& city2);
vector<string> getItinerary(unsigned int length);
private:
int num_city_names, xsize, ysize;
unordered_map<string, float> xpos, ypos;
vector<string> cities;
unordered_map<string, unordered_map<string, float>> distances;
mt19937 gen; // Mersenne-Twister random number engine
};
#endif
middleearth.cpp
#include "middleearth.h"
#include <algorithm>
#include <array>
#include <cstdlib>
#include <cmath>
// New shuffle method that uses the Mersenne Twister engine
void shuffle (vector<string>::iterator first, vector<string>::iterator last, mt19937& g) {
for (auto i=(last-first)-1; i>0; --i) {
unsigned int n = (g() / (double) g.max())*distance(first,last);
swap (first[i], first[n]);
}
}
// The list of all the place names that we'll be using
const array<string, 40> all_city_names{
// human towns, cities and strongholds
"Bree", // a human and hobbit town between the Shire and Rivendell
"Isengard", // the tower fortress where Saruman resided; Gandalf was imprisoned there.
"Minas Tirith", // capital of Gondor, the "white city"; home to Boromir, Denethor, and later, Aragorn
"Osgiliath", // city on the river Anduin; is at the other end of Pelennor Fields from M. Tirith
"Edoras", // the capital city of Rohan, where King Theoden resides
"Helm's Deep", // fortress of Rohan, it is where the people of Edoras fled to from the orc invasion
"Dunharrow", // a refuge of Rohan, it is where Elrond presents the sword to Aragorn in the movie
// dwarf cities
"Moria", // the enormous dwarven underground complex that the Fellowship traveled through
// elvish cities
"Lothlorien", // the elvish tree-city, home of Lady Galadriel and Lord Celeborn
"Rivendell", // the elvish city that is home to Lord Elrond
"The Grey Havens", // the port city on the western coast from which the elves travel westward
// hobbit villages
"Bucklebury", // a Shire village, it has a ferry across the Brandywine River that the Hobbits use
"Bywater", // a Shire village, it is the site of the Battle of Bywater (removed from the movie)
"Hobbiton", // a Shire village, it is home to Bilbo and, later, Frodo
"Michel Delving", // a Shire village, it is the chief town of the Shire
// Mordor places
"Orodruin", // Mount Doom in Mordor, it is where the Ring was made, and later, unmade
"Barad-Dur", // Sauron's fortress that was part castle, part mountain
"Minas Morgul", // formerly the Gondorian city of Minas Ithil; renamed when Sauron took it over
"Cirith Ungol", // the mountianous pass that Sam & Frodo went through; home of Shelob
"Gorgoroth", // the plains in Mordor that Frodo & Sam had to cross to reach Mount Doom
// places that are not cities
"Emyn Muil", // the rocky region that Sam & Frodo climb through after leaving the Fellowship
"Fangorn Forest", // the forest where Treebeard (and the other Ents) live
"Dagorlad", // great plain/swamp between Emyn Muil & Mordor where a great battle was fought long ago
"Weathertop", // the tower between Bree and Rivendell where Aragorn and the Hobbits take refuge
"Gladden Fields", // this is where the Ring is lost in the River Anduin, after Isildur is ambushed and killed by Orcs
"Entwash River", // a river through Rohan, which flows through Fangorn Forest
"River Isen", // river through the Gap of Rohan; Theoden's son was slain in a battle here.
"The Black Gate", // huge gate to Mordor that Aragorn and company attack as the ring is destroyed
"The Old Forest", // a forest to the west of the Shire (adventures there were removed from the movie)
"Trollshaws", // area to the west of Rivendell that was home to the trolls that Bilbo met
"Pelennor Fields", // great plain between M. Tirith and Osgiliath; site of the Battle of M. Tirith
"Hollin", // the empty plains that the Fellowship crosses between Rivendell and Moria
"Mirkwood", // Legolas' forest home; Bilbo travels there in 'The Hobbit'.
"Misty Mountains", // the north-south moutain range that runs through Middle-earth
"Prancing Pony", // an inn in Bree where the hobbits tried to meet Gandalf, but meet Aragorn instead
// places from the Hobbit book and movies
"Laketown", // also called Esgaorth, it is the town of men on the Long Lake near Erebor
"Dale", // the town of men outside Erebor, destroyed by Smaug long before the Hobbit story
"Erebor", // the Elvish name for the Lonely Mountain, where the dwarves had their fortress
"Beorn's House", // Beorn is the shape-shifter who shelters the dwarf party
"Dol Guldur", // fortress in Mirkwood where Sauron, as the Necromancer, hid during most of the Hobbit
};
// Iluvatar, the creator of Middle-Earth
MiddleEarth::MiddleEarth(int xsize, int ysize, int num_cities, int seed) {
this->xsize = xsize;
this->ysize = ysize;
// set up the random number generator
gen.seed(seed == -1 ? random_device{}() : seed);
// count the number of cities in the array
this->num_city_names = all_city_names.size();
if (num_cities > num_city_names) {
cout << "There are only " << num_city_names << " city names, so "
<< num_cities << " cities cannot be created." << endl;
cout << "Exiting." << endl;
exit(0);
}
if (num_cities < 5) {
num_cities = 5;
}
// copy all the cities into a mutable vector
this->cities = vector<string>(all_city_names.begin(), all_city_names.end());
shuffle(cities.begin(), cities.end(), gen); // shuffle all the cities
cities.erase(cities.begin() + num_cities, cities.end()); // then remove the ones we won't be using
// compute random city positions
for (auto city : cities) {
xpos.emplace(city, (gen() / (double) gen.max()) * xsize);
ypos.emplace(city, (gen() / (double) gen.max()) * ysize);
}
// compute the 2-d distance array
// we assume that num_cities < xsize * ysize
for (auto city1 : cities) {
for (auto city2 : cities) {
distances[city1].emplace(city2, sqrt((xpos[city2] - xpos[city1]) * (xpos[city2] - xpos[city1]) +
(ypos[city2] - ypos[city1]) * (ypos[city2] - ypos[city1])));
}
}
}
// The Mouth of Sauron!
// Prints out info on the created 'world'
void MiddleEarth::print() {
cout << "there are " << num_city_names
<< " locations to choose from; we are using " << cities.size() << endl;
cout << "they are: " << endl;
for (auto city : cities) {
cout << "\t" << city << " # (" << xpos[city] << ", " << ypos[city]
<< ")" << endl;
}
}
// Prints a tab-separated table of the distances,
// which can be loaded into Excel or similar
void MiddleEarth::printTable() {
cout << "Table: " << endl << endl << "Location\txpos\typos\t";
for (auto city : cities) {
cout << city << "\t";
}
cout << endl;
for (auto city1 : cities) {
cout << city1 << "\t" << xpos[city1] << "\t" << ypos[city1] << "\t";
for (auto city2 : cities) {
cout << distances[city1][city2] << "\t";
}
cout << endl;
}
}
// This method returns the distance between the two passed cities.
// If we assume that the hash table (i.e. the map) is O(1),
// then this method call is also O(1)
float MiddleEarth::getDistance(const string& city1, const string& city2) {
return distances[city1][city2];
}
// Returns the list of cities to travel to.
// The first city is the original start point as well as the end point.
// The number of cities passed in does not include this start/end point
// (so there will be length+1 entries in the returned vector).
vector<string> MiddleEarth::getItinerary(unsigned int length) {
// check parameter
if (length >= cities.size()) {
cout << "You have requested an itinerary of " << length
<< " cities; you cannot ask for an itinerary of more than length "
<< cities.size() - 1 << endl;
exit(0);
}
length++; // to account for the start point
// we need to make a deep copy of the cities vector
vector<string> itinerary(cities.begin(), cities.end());
// shuffle, erase unneeded ones, and return the itinerary
shuffle(itinerary.begin(), itinerary.end(), gen);
itinerary.erase(itinerary.begin() + length, itinerary.end());
return itinerary;
}
topological.cpp
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <list>
#include <stack>
#include <string>
#include <map>
using namespace std;
/**
#date 11/16/2020
*/
/** #brief
*/
class Graph
{
public:
Graph(int vert);
/** #brief adds an edge to the list
* #param string v
* #param string w
* #param map<string, int> m
*
*/
void addEdge(string v, string w, map<string, int> m);
void printSort();
private:
int vertices;
list<int> *myList;
void sort(int v, stack<int> &myStack, bool visited[]);
map<int, string> myMap;
};
Graph::Graph(int vert) {
vertices = vert;
myList = new list<int>[vertices];
}
void Graph::addEdge(string v, string w, map<string, int> m) {
int loc1 = m[v];
int loc2 = m[w];
myMap[loc1] = v;
myMap[loc2] = w;
myList[loc1].push_back(loc2);
}
void Graph::sort(int v, stack<int> &myStack, bool visited[]) {
visited[v] = true;
list<int>::iterator i;
for(i = myList[v].begin(); i != myList[v].end(); ++i) {
if(!visited[*i]) {
sort(*i, myStack, visited);
}
}
myStack.push(v);
}
void Graph::printSort() {
stack<int> myStack;
bool *visited = new bool[vertices];
for(int i = 0; i < vertices; i++) {
visited[i] = false;
}
for(int i = 0; i < vertices; i++) {
if(visited[i] == false)
sort(i, myStack, visited);
}
while(myStack.empty() == false) {
int x = myStack.top();
string output = myMap[x];
cout << output << " ";
myStack.pop();
}
}
int main (int argc, char **argv) {
if ( argc != 2 ) {
cout << "Must supply the input file name as the one and only parameter" << endl;
return 1;
}
ifstream file(argv[1], ifstream::binary);
ifstream file1(argv[1], ifstream::binary);
if ( !file.is_open() ) {
cout << "Unable to open file '" << argv[1] << "'." << endl;
return 1;
}
string s1, s2;
int count = 0;
list <string> edges;
while(!file.eof()) {
file >> s1;
file >> s2;
if(s1 == "0" && s2 == "0") {
break;
}
edges.push_back(s1);
edges.push_back(s2);
}
file.close();
edges.sort();
edges.unique();
int size = edges.size();
map<string, int> myMap;
Graph myGraph(size);
list<string>::iterator i;
for(i = edges.begin(); i != edges.end(); i++) {
string s = *i;
myMap[s] = count;
count++;
}
while(!file1.eof()) {
file1 >> s1;
file1 >> s2;
if(s1 == "0" && s2 == "0") {
break;
}
myGraph.addEdge(s1, s2, myMap);
}
myGraph.printSort();
cout<<endl;
file1.close();
return 0;
}
You are confusing yourself. You have your solution in edges. There isn't a reason to read the data a second time. For example, you can simply output sorted/unique elements of edges, e.g. the modifications to your code are:
int main (int argc, char **argv) {
if ( argc != 2 ) {
cout << "Must supply the input file name as the one and only parameter" << endl;
return 1;
}
ifstream file(argv[1], ifstream::binary);
// ifstream file1(argv[1], ifstream::binary);
if ( !file.is_open() ) {
cout << "Unable to open file '" << argv[1] << "'." << endl;
return 1;
}
string s1, s2;
// int count = 0;
list <string> edges;
while(file >> s1 && file >> s2) {
if(s1 == "0" && s2 == "0") {
break;
}
edges.push_back(s1);
edges.push_back(s2);
}
file.close();
edges.sort();
edges.unique();
// int size = edges.size();
// map<string, int> myMap;
bool first = true;
for (const auto& n : edges) {
if (!first)
cout.put(' ');
cout << n;
first = false;
}
cout.put('\n');
// Graph myGraph(size);
// list<string>::iterator i;
// for(i = edges.begin(); i != edges.end(); i++) {
// string s = *i;
// myMap[s] = count;
// count++;
// }
//
// while(file1 >> s1 && file1 >> s2) {
// if(s1 == "0" && s2 == "0") {
// break;
// }
// myGraph.addEdge(s1, s2, myMap);
// }
//
// myGraph.printSort();
// cout<<endl;
// file1.close();
return 0;
}
(note: how while (!file.eof())) was replaced with while(file >> s1 && file >> s2))
Example Use/Output
With your sample data in dat/topological.txt, you would receive:
$ ./bin/topological dat/topological.txt
cs1110 cs2102 cs2110 cs2150 cs3330 cs4414
If you are having problems editing your code, then you can do things much easier with a std::set, e.g.
#include <iostream>
#include <fstream>
#include <string>
#include <set>
int main (int argc, char **argv) {
if ( argc != 2 ) {
std::cerr << "Must supply the input file name as the one and only parameter\n";
return 1;
}
std::set<std::string> strset {};
std::string s {};
std::ifstream f (argv[1]);
if (!f.good()) {
std::cerr << "file open failed.\n";
return 1;
}
while (f >> s && s != "0")
strset.insert(s);
bool first = true;
for (const auto& unique : strset) {
if (!first)
std::cout.put(' ');
std::cout << unique;
first = false;
}
std::cout.put('\n');
}
(same answer)
This is when i used the main you gave me:
enter image description here
This is when i added (Yes. after edges.unique(); you can simply do. bool first = true; for (const auto& n : edges) { if (!first) cout.put(' '); cout << n; first = false; } cout.put('\n');):
enter image description here
the first line on output is correct, i dont want the line under it
Related
I have to read two text files and then compare words from second file with the first one. Then , I have to display KnownWords which are same words from both files and the remaining words which are not same are UnknownWords. Next Step is, I have to display most frequent known words in DisplayMostFreqKnownWords() and unknown words in DisplayMostFreqUnknownWords() functions. I have successfully completed DisplayMostFreqKnownWords() and so far Output is alright. I copied the same code from DisplayMostFreqKnownWords() to DisplayMostFreqUnknownWords() but in this is function it is not showing anything in the output. I dont know what is wrong. Can someone figure this one out.
Output is:
Displaying most frequent known words
Word Count
the 19
a 14
of 11
artificial 11
that 10
to 7
signal 7
and 7
in 6
they 5
Displaying most frequent unknown words
Word Count
Header file:
typedef map<string, vector<int> > WordMap;
typedef WordMap::iterator WordMapIter;
class WordStats
{
public:
WordStats();
void ReadDictionary();
void DisplayDictionary();
void ReadTxtFile();
void DisplayKnownWordStats();
void DisplayUnknownWordStats();
void DisplayMostFreqKnownWords();
void DisplayMostFreqUnknownWords();
private:
WordMap KnownWords;
WordMap UnknownWords;
WordMapIter Paragraph;
set<string> Dictionary;
char Filename[256];
}
My program:
// Displays 10 most frequent words in KnownWords
void WordStats::DisplayMostFreqKnownWords(){
int count;
multimap<int,string > displayFreqWords;// new map with int as key
(multimap because key could occur more than once)
multimap<int,string >::reverse_iterator rit = displayFreqWords.rbegin();
for (Paragraph = KnownWords.begin(); Paragraph != KnownWords.end();
++Paragraph){ // iterate map again
string word = (*Paragraph).first;
int cnt = (*Paragraph).second.size();
displayFreqWords.insert(pair<int,string>(cnt,word));
}
// multimap<int,string>::iterator rit; // iterator for new map
cout <<" Word Count\n";
for(; count<=10 && rit!=displayFreqWords.rend(); rit++, ++count){
string word = (*rit).second;
int cnt = (*rit).first;
cout << setw(15) << word << setw(10) << cnt << endl;
}
}
// Displays 10 most frequent words in UnknownWords
void WordStats::DisplayMostFreqUnknownWords(){
int count;
multimap<int,string > displayFreqUnknownWords;
multimap<int,string >::reverse_iterator rrit =
displayFreqUnknownWords.rbegin();
for (Paragraph = UnknownWords.begin(); Paragraph !=
UnknownWords.end(); ++Paragraph){
string word = (*Paragraph).first;
int cnt = (*Paragraph).second.size();
displayFreqUnknownWords.insert(pair<int,string>(cnt,word));
}
// multimap<int,string>::iterator rit; // iterator for new map
cout <<" Word Count\n";
for(; count<=10 && rrit!=displayFreqUnknownWords.rend(); rrit++, ++count){
string wrd = (*rrit).second;
int ccnt = (*rrit).first;
cout << setw(15) << wrd << setw(10) << ccnt << endl;
}
}
Here's a way to express what I think is your use case. I have used c++17 tuple expansion.
I have used unordered_map to deduce which words are known or unknown, and two multimaps to determine known and unknown word frequency.
Hope it's helpful.
#include <sstream>
#include <tuple>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <iterator>
#include <map>
#include <iostream>
#include <iomanip>
#include <fstream>
// Set this to 1 to run a static test
#define TESTING 0
#if TESTING
using input_type = std::istringstream;
std::tuple<input_type, input_type> open_inputs() {
return {
std::istringstream("the big black cat sat on the grey mat"),
std::istringstream("the gold small cat lay on the purple mat")
};
}
#else
using input_type = std::ifstream;
std::tuple<input_type, input_type> open_inputs() {
return {
std::ifstream("left_file.txt"),
std::ifstream("right_file.txt"),
};
}
#endif
struct Counts {
int left_count = 0, right_count = 0;
int total() const {
return left_count + right_count;
}
bool is_known() const {
return left_count && right_count;
}
};
template<class F>
void for_each_word_in_file(std::istream &is, F f) {
std::for_each(std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>(),
f);
}
int main() {
// open files
auto[left, right] = open_inputs();
auto known_words = std::unordered_map<std::string, Counts>();
// count words in each file
for_each_word_in_file(left, [&known_words](auto &&word) {
++known_words[word].left_count;
});
for_each_word_in_file(right, [&known_words](auto &&word) {
++known_words[word].right_count;
});
// map counts to words, in descending order, allowing multiple entries of the same count
std::multimap<int, std::string, std::greater<>> known_ordered, unknown_ordered;
// iterate all words seen, putting into appropriate map
for (auto&&[word, counts] : known_words) {
(counts.is_known() ? known_ordered : unknown_ordered)
.emplace(counts.total(), word);
}
// emit results
std::cout << "Known words by frequency\n";
for (auto&&[freq, word] : known_ordered) {
std::cout << std::setw(15) << word << " " << freq << '\n';
}
std::cout << "\nUmknown words by frequency\n";
for (auto&&[freq, word] : unknown_ordered) {
std::cout << std::setw(15) << word << " " << freq << '\n';
}
}
I'm working on a program that mimics an "Animal Adoption Agency." I read from the file, which contains a list of animal names, breed, age, price, and sex. I have two files, one each for cats and dogs.
The user has an option to sort the list by the above listed categories. I have a for loop currently that will accurately sort the category they choose; however, the other categories will not order themselves accordingly. I'm not sure how to go about this.
Here's a condensed version of my code, that allows access only to the dogs portion and sorting by name, rather than have a choice of how to sort.
#include <iostream>
#include <fstream>
#include <istream>
#include <cctype>
#include <string>
#include <string.h>
#include <cstring>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
int animalMenu, animalCount, animAge[50], animPrice[50], entry = 0, total;
string animType, animName[50], animBreed[50], animSex[50], takeHomeWith;
ifstream animalInform;
const int WIDTH = 8, BIG_WIDTH = 12;
void sortingHat(string[]);
void innerSorting(string[], int);
int main() {
animalInform.open("Dog Information.txt");
animType = "dogs";
// SET NUMBER OF ANIMALS IN FILE
animalInform >> animalCount;
cout << "There are " << animalCount << " " << animType << "! \n";
// SETS ALL THE VALUES BY READING FROM FILE
for (int entry = 0; entry < animalCount; entry++) {
animalInform >> animName[entry] >> animBreed[entry] >> animAge[entry] >> animPrice[entry] >> animSex[entry];
cout << setw(BIG_WIDTH) << animName[entry] << setw(BIG_WIDTH) << animBreed[entry] << setw(WIDTH) << animAge[entry] << setw(WIDTH) << animPrice[entry] << setw(WIDTH) << animSex[entry] << endl;
}
// CLOSE FILE
animalInform.close();
// CALL FUNCTION TO SORT (BY NAME ONLY)
sortingHat(animName);
cout << endl;
// DISPLAY NEWLY SORTED LIST
for (int entry = 0; entry < animalCount; entry++) {
cout << setw(BIG_WIDTH) << animName[entry] << setw(BIG_WIDTH) << animBreed[entry] << setw(WIDTH) << animAge[entry] << setw(WIDTH) << animPrice[entry] << setw(WIDTH) << animSex[entry] << endl;
}
system("pause");
}
void sortingHat(string sortingString[])
{ // SORTS DATA AND PUTS IT IN ORDER, ALPHABETICAL --
for (int outer = 0; outer <= animalCount; outer++)
{
for (int entry = 0; entry <= (animalCount - 2); entry++) {
string temporary[50];
if (sortingString[entry] > sortingString[entry + 1])
innerSorting(sortingString, entry);
}
}
}
void innerSorting(string sorter[], int entry)
{
string temporary[50];
temporary[entry] = sorter[entry];
sorter[entry] = sorter[entry + 1];
sorter[entry + 1] = temporary[entry];
}
So I obviously don't have anything that would make the other entries follow suit.
So if I choose name to be sorted, my output (this is what is written in my file) will go from
Brienne Shepard 6 $150 F
Jon Labrador 3 $200 M
Aemon ShihTzu 10 $50 M
to
Aemon Shepard 6 $150 F
Brienne Labrador 3 $200 M
Jon ShihTzu 10 $50 M
And I want it to do this (if choosing to sort by name):
Aemon ShihTzu 10 $50 M
Brienne Shepard 6 $150 F
Jon Labrador 3 $200 M
If I have understood you correctly you have a set of arrays that contain animal characteristics. And you are going to sort by one characteristics such a way that all arrays would be sorted. If so then you can write one common function for all arrays.
For example
enum SortType { SortByName, /* other types of sorting */, SortByAge };
//...
void bubble_sort( std::string animName[],
/* other characteristics */
int animAge[],
size_t n,
SortType type )
{
for ( size_t last; not ( n < 2 ); n = last )
{
for ( size_t i = last = 1; i < n; i++ )
{
bool less = false;
switch ( type )
{
case SortByName:
less = animName[i] < animName[i-1];
break;
/* other cases */
case SortByAge:
less = animAge[i] < animAge[i-1];
break;
}
if ( less )
{
/* swapping elements of all the arrays */
last = i;
}
}
}
}
Take into account that this swap function
void innerSorting(string sorter[], int entry)
{
string temporary[50];
^^^^^^^^^^^^^^^^^^^^
temporary[entry] = sorter[entry];
sorter[entry] = sorter[entry + 1];
sorter[entry + 1] = temporary[entry];
}
should not use an array of strings. It can be written like
void innerSorting(string sorter[], size_t entry)
{
string temporary;
^^^^^^^^^^^^^^^^^
temporary = sorter[entry];
sorter[entry] = sorter[entry + 1];
sorter[entry + 1] = temporary;
}
I've been looking at this for a while in the debugger while Googling around, but I think I've stumbled upon some C++ behavior that I'm not familiar with. I'm going to give a quick outline on what I'm doing and what/where the problem is. I'll put code block below.
The rough outline of what's happening is:
Created a custom class (LogReader) to handle a single log file.
LogReader contains a pointer to an ifstream (ifstream *log_file)
The ifstream is used with getline() in the constructor, this works fine.
The LogReader is placed in a vector.
The code below for main.cpp is using the LogReader directly (without the vector). The segfault occurs in both cases.
LogReader.advance() is called. getline() is used in this function. The segfault occurs here (commented in LogReader.cpp).
Thanks for any help on what C++ behaviors I'm missing that might be causing this!
EDIT: Not placing the LogReader into a vector removes the segfault (failing elsewhere now, but not a problem). The change is commenting the following line out in main.cpp
readers.push_back(&label_reader);
I guess now the question is why using std::vector is causing this problem.
LogReader.h
#ifndef LOGREADER
#define LOGREADER
using namespace std;
class LogReader {
private:
LogReader(){} // private default constructor
public:
ifstream *log_file; // file the log is read from
vector<int> val_locations; // offsets in line for values
string next_line; // next line from the file
int current_time; // time for most recent reading
string current_line;
int next_time; // what is the next time in the file
vector<string> current_vals; // what the current vals are
LogReader(string log_loc, vector<int> offsets); // given a file to start on
bool advance(int new_time); // advance the log reader, return true if advanced
bool has_more(); // is there more in the log
};
#endif
LogReader.cpp
// c++ imports
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// my imports
#include "LogReader.h"
#include "functions.h"
using namespace std;
LogReader::LogReader(string log_loc, vector<int> offsets){
// make the file reader
ifstream lf(log_loc);
log_file = &lf;
// pull out the first line
getline(*log_file, current_line);
cout << current_line << endl;
// get the set of current values
val_locations = offsets;
for(int i = 0; i < val_locations.size(); i++) {
current_vals.push_back(get_line_part(current_line,
val_locations.at(i)));
}
// get the current time
current_time = stoi(get_line_part(current_line, 0));
// pull down the next line
getline(*log_file, next_line);
cout << next_line << endl;
// get the next time
next_time = stoi(get_line_part(next_line, 0));
}
bool LogReader::advance(int new_time){
if(new_time < next_time)
return false; // nothing to do, current still good
cout << "can check time" << endl;
// update the time and values
current_time = next_time;
current_line = next_line;
current_vals.clear();
cout << "can do housekeeping" << endl;
for(int i = 0; i < val_locations.size(); i++) {
current_vals.push_back(get_line_part(next_line,
val_locations.at(i)));
}
cout << "can push in new values" << endl;
// move the line
next_line.clear();
if(!getline(*log_file, next_line)) { // **SEGFAULT**
// no more lines
cout << "no more lines" << endl;
next_line.clear();
next_time = -1;
return true;
}
cout << "got the line" << endl;
// update the time as well
next_time = stoi(get_line_part(next_line, 0));
return true;
}
bool LogReader::has_more(){
return next_time != -1;
}
main.cpp
// c imports
#include <time.h>
// c++ imports
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
// my imports
#include "LogReader.h"
#include "functions.h"
// custom shorter namespaces
namespace bfs = boost::filesystem;
// used namespaces
using namespace std;
void update_line(int *current_time, string *current_line,
ifstream *current_file){
if(!getline(*current_file, *current_line)){
*current_time = -1;
current_line->clear();
return;
}
try {
*current_time = stoi(get_line_part(*current_line, 0));
} catch (int e) {
cout << "update line, bad stoi on time" << endl;
cout << *current_line << endl;
throw e;
}
}
void update_vals(vector<float*> vals, string line) {
for(int i = 0; i < vals.size(); i++) {
// offset for fact that first two are time and sensor
try {
*(vals.at(i)) = stof(get_line_part(line, 2 + i));
} catch (int e) {
cout << "update_vals, bad stof for " << i << endl;
cout << line << endl;
throw e;
}
}
}
string get_correct_file(string name, vector<string> options) {
for(int i =0; i < options.size(); i++) {
string option = options.at(i);
if(boost::algorithm::contains(option, name)){
return option;
}
}
return string("");
}
int main(int argc, char* argv[]) {
// open the base dir
bfs::path base_dir("log/");
if(!bfs::exists(base_dir) && !bfs::is_directory(base_dir)){
cout << "Bad base directory" << endl;
return 1;
}
// create a vector of the possible traces
vector<string> traces;
for(bfs::directory_iterator iter(base_dir);
iter != bfs::directory_iterator(); iter++) {
stringstream trace_path;
trace_path << iter->path().string();
traces.push_back(trace_path.str());
}
int trace_index = user_choose_option(traces);
// load that directory
bfs::path trace_dir(traces.at(trace_index));
if(!bfs::exists(base_dir) && !bfs::is_directory(base_dir)){
cout << "Selected a bad trace directory" << endl;
return 1;
}
// get the image directory
cout << "loading image directory" << endl;
string img_path_string = trace_dir.string();
stringstream img_path_stream;
img_path_stream << img_path_string << "/img/";
bfs::path img_dir(img_path_stream.str());
if(!bfs::exists(img_dir) && !bfs::is_directory(img_dir)){
cout << "no image directory" << endl;
return 1;
}
// get image list, ends up in sorted order from naming conventions
cout << "getting image paths" << endl;
vector<string> image_paths;
for(bfs::directory_iterator iter(img_dir);
iter != bfs::directory_iterator(); iter++) {
stringstream image_path;
image_path << iter->path().string();
image_paths.push_back(image_path.str());
}
// get the data traces
cout << "loading data traces" << endl;
vector<string> log_paths;
vector<string> label_paths;
string trace_path_string = trace_dir.string();
for(bfs::directory_iterator iter(trace_path_string);
iter != bfs::directory_iterator(); iter++) {
string cur_file = iter->path().string();
cout << cur_file << endl;
if(boost::algorithm::contains(cur_file, "label-")) {
label_paths.push_back(cur_file);
} else if(boost::algorithm::contains(cur_file, "log-")) {
log_paths.push_back(cur_file);
}
}
cout << endl;
// temp for reading in line parts
// istringstream temp;
cout << "getting log readers" << endl;
// choose the label file to use, get first line
int label_index = user_choose_option(label_paths);
vector<int> label_offsets;
label_offsets.push_back(1);
LogReader label_reader(label_paths.at(label_index), label_offsets);
/*
ifstream label_file(label_paths.at(label_index));
string label_line;
getline(label_file, label_line);
int label_time;
temp.clear();
temp.str(get_line_part(label_line, 0));
temp >> label_time;
string label_current = get_line_part(label_line, 1);
*/
/*
// get the accel
string accel_path = get_correct_file("accel", log_paths);
vector<int> accel_offsets;
accel_offsets.push_back(2);
accel_offsets.push_back(3);
accel_offsets.push_back(4);
LogReader accel_reader(accel_path, accel_offsets);
*/
vector<LogReader*> readers;
vector<bool> updated;
readers.push_back(&label_reader);
updated.push_back(true);
// readers.push_back(&accel_reader);
// updated.push_back(true);
int l_time = current_time_min(readers);
while(label_reader.has_more() ){ // || accel_reader.has_more()) {
// figure out what time to advance to
int n_time;
cout << label_reader.has_more() << endl;
if(same_current_time(readers)) {
n_time = next_time_min(readers);
} else {
n_time = current_time_nextmin(readers);
}
cout << n_time << endl;
label_reader.advance(n_time);
cout << label_reader.current_line << endl;
/*
// advance all the readers
for(int i = 0; i < readers.size(); i++) {
cout << "loop " << i << endl;
// keep track of which values updated
readers.at(i);
cout << "can get from vector" << endl;
bool advanced = readers.at(i)->advance(n_time);
cout << advanced << endl;
if(advanced) {
updated.at(i) = true;
} else {
updated.at(i) = false;
}
}
// sanity check printing
for(int i = 0; i < readers.size(); i++) {
cout << readers.at(i)->current_line << endl;
}
*/
// deal with statistics here
}
/*
ifstream accel_file(accel_path);
string accel_line;
getline(accel_file, accel_line);
int accel_time;
temp.clear();
temp.str(get_line_part(accel_line, 0));
temp >> accel_time;
float accel_current_x = stof(get_line_part(accel_line, 2));
float accel_current_y = stof(get_line_part(accel_line, 3));
float accel_current_z = stof(get_line_part(accel_line, 4));
vector<float*> accel_vals;
accel_vals.push_back(&accel_current_x);
accel_vals.push_back(&accel_current_y);
accel_vals.push_back(&accel_current_z);
// get the sprox
string sprox_path = get_correct_file("sprox", log_paths);
ifstream sprox_file(sprox_path);
string sprox_line;
getline(sprox_file, sprox_line);
int sprox_time;
temp.clear();
temp.str(get_line_part(sprox_line, 0));
temp >> sprox_time;
float sprox_current = stof(get_line_part(sprox_line, 2));
vector<float*> sprox_vals;
sprox_vals.push_back(&sprox_current);
// get the lprox
string lprox_path = get_correct_file("lprox", log_paths);
ifstream lprox_file(lprox_path);
string lprox_line;
getline(lprox_file, lprox_line);
int lprox_time;
temp.clear();
temp.str(get_line_part(lprox_line, 0));
temp >> lprox_time;
float lprox_current = stof(get_line_part(lprox_line, 2));
vector<float*> lprox_vals;
lprox_vals.push_back(&lprox_current);
// get the light
string light_path = get_correct_file("light", log_paths);
ifstream light_file(light_path);
string light_line;
getline(light_file, light_line);
int light_time;
temp.clear();
temp.str(get_line_part(light_line, 0));
temp >> light_time;
float light_current = stof(get_line_part(light_line, 2));
vector<float*> light_vals;
light_vals.push_back(&light_current);
*/
// int time_current = min(label_time, min(sprox_time,
// min(lprox_time, min(accel_time,
// light_time))));
/*
// variables for processing here
int total_time = 0;
map<string, int> label_counts;
while(label_time != -1 || accel_time != -1 || sprox_time != -1
|| lprox_time != -1 || light_time != -1) {
time_current++;
if(label_time != -1 && time_current > label_time) {
update_line(&label_time, &label_line, &label_file);
if(label_line.size() > 0) // if last label, don't overwrite
label_current = get_line_part(label_line, 1);
}
if(accel_time != -1 && time_current > accel_time) {
update_line(&accel_time, &accel_line, &accel_file);
if(accel_line.size() > 0) // if last line, don't overwrite
update_vals(accel_vals, accel_line);
}
if(sprox_time != -1 && time_current > sprox_time) {
update_line(&sprox_time, &sprox_line, &sprox_file);
if(sprox_line.size() > 0) // if last line, don't overwrite
update_vals(sprox_vals, sprox_line);
}
if(lprox_time != -1 && time_current > lprox_time) {
update_line(&lprox_time, &lprox_line, &lprox_file);
if(lprox_line.size() > 0) // if last line, don't overwrite
update_vals(lprox_vals, lprox_line);
}
if(light_time != -1 && time_current > light_time) {
update_line(&light_time, &light_line, &light_file);
if(light_line.size() > 0) // if last line, don't overwrite
update_vals(light_vals, light_line);
}
// Processing happens here
total_time++;
if(label_counts.count(label_current) == 0)
// not in map
label_counts[label_current] = 0;
label_counts[label_current]++;
}
// post processing happens here
cout << "Labels Counts:" << endl;
for(map<string, int>::iterator it = label_counts.begin();
it != label_counts.end(); it++) {
cout << it->first << " -> " << it->second << " -> ";
cout << 1.0 * it->second / total_time << endl;
}
*/
}
Your program exhibits undefined behavior since you are using a pointer to an object that has been deleted.
ifstream lf(log_loc);
log_file = &lf;
if gets deleted when the constructor returns and you are still holding on to a pointer to the object.
Change log_file to an object instead of a pointer.
i am creating a somekind of rpg battle, where the program reads the input from a .txt file. i created the code but when i want to start the battle, it gave me an error vector subscript out of range. can anyone help me how to fix this? thank you very much :) here is the code. I included everything just so you could get a full context but the main problem I believe is in my while loop in the main cpp, if you want to just skip down to there.
and so that we are on the same track, the content of the txt file for lamanite(hitpoints and regen points) is
8 2
7 3
6 1
for nephite its
10 3
12 4
11 5
here is my warrior.h file
#pragma once
#include <string>
using namespace std;
class warrior
{
public:
warrior ();
warrior (int h, int r);
int getDamage() const;
void takeDamage(int damage);
int getCurrentHP() const;
void regenerate();
string tostring(int h, int r);
private:
int HitPoints;
int RegPoints;
int damage;
};
here is my warrior cpp
#include "warrior.h"
#include <string>
#include <iostream>
warrior::warrior(int h, int r)
{
HitPoints = h;
RegPoints = r;
}
int warrior::getDamage() const
{
int damage = rand () % HitPoints;
return damage;
}
void warrior::takeDamage(int damage)
{
HitPoints = HitPoints - damage;
}
int warrior::getCurrentHP() const
{
return HitPoints;
}
void warrior::regenerate()
{
HitPoints = HitPoints + rand () % (RegPoints);
}
string warrior::tostring(int h, int r)
{
return 0;
}
my main file
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <ctime>
#include "warrior.h"
using namespace std;
void main ()
{
srand(time(0));
ifstream input1;
cout << "input file name nephite: ";
string filename;
cin >> filename;
input1.open(filename);
int HP1, RP1;
vector <warrior*> nephites;
while (input1 >> HP1 >> RP1)
{
nephites.push_back(new warrior(HP1, RP1));
}
cout << nephites.size() << endl;
ifstream input2;
cout << "input file name lamanite : ";
string filename2;
cin >> filename2;
input2.open(filename2);
int HP2, RP2;
vector <warrior*> lamanites;
while (input2 >> HP2 >> RP2)
{
lamanites.push_back(new warrior(HP2, RP2));
}
cout << lamanites.size() << endl;
cout << endl << "Battle" << endl;
warrior nephitesw = warrior (HP1,RP1);
warrior lamanitesw = warrior (HP2,RP2);
while ((nephites.size() > 0) && (lamanites.size() > 0))
{
int rN = rand () % nephites.size();
int rL = rand () % lamanites.size();
cout << rN << "xx" << rL << endl; // so that i know what rN and rL is
while((nephites[rN]->getCurrentHP() > 0) && (lamanites[rL]->getCurrentHP() > 0)) // the program can't execute this part of the code
{
nephites[rN]->takeDamage(lamanites[rL]->getDamage());
lamanites[rL]->takeDamage(nephites[rN]->getDamage());
if(lamanites[rL]->getCurrentHP() > 0)
{
lamanites[rL]->regenerate();
}
else
{
lamanites.erase(lamanites.begin() + (rL));
}
if(nephites[rN]->getCurrentHP() > 0)
{
nephites[rN]->regenerate();
}
else
{
nephites.erase(nephites.begin() + (rN));
}
}
cout << "NEP HP: " << nephites[rN]->getCurrentHP() << " " << "LAM HP: " << lamanites[rL]->getCurrentHP() << endl;
}
system ("Pause");
}
You have a while loop that tests for a certain properties of nephites[rN] and lamanites[rL]:
while((nephites[rN]->getCurrentHP() > 0) && (lamanites[rL]->getCurrentHP() > 0)
{
// ...
}
But inside that loop you might erase those elements:
{lamanites.erase(lamanites.begin() + (rL));}
// ...
{nephites.erase(nephites.begin() + (rN));}
At the very least, after one of those erase operations you'll be testing a different nephite or lamanite object on the next loop iteration (which may or may not be what you want), but if you've erased the last element in the container, you have the problem that the index is now out of range.
You are looping until either nephites[rN]->getCurrentHP() <= 0 or lamanites[rL]->getCurrentHP() <= 0. However, whichever one drops to 0 first will be deleted from the vector:
// ...
{lamanites.erase(lamanites.begin() + (rL));}
// ...
{nephites.erase(nephites.begin() + (rN));}
If rN == nephites.size() or rN == lamanites.size() (which will definitely happen when the size is 1 and may randomly happen earlier), this will cause you to index out of the vector when you test the loop.
To quickly solve the problem, move the code that removes the warrior(s) from the vector out of the loop:
while((nephites[rN]->getCurrentHP() > 0) && (lamanites[rL]->getCurrentHP() > 0))
{
nephites[rN]->takeDamage(lamanites[rL]->getDamage());
lamanites[rL]->takeDamage(nephites[rN]->getDamage());
if(lamanites[rL]->getCurrentHP() > 0)
{
lamanites[rL]->regenerate();
}
if(nephites[rN]->getCurrentHP() > 0)
{
nephites[rN]->regenerate();
}
}
cout << "NEP HP: " << nephites[rN]->getCurrentHP() << " " << "LAM HP: " << lamanites[rL]->getCurrentHP() << endl;
// *****
// Move the erasures out of the loop
// *****
if(lamanites[rL]->getCurrentHP() <= 0)
{
lamanites.erase(lamanites.begin() + (rL));
}
if(nephites[rN]->getCurrentHP() <= 0)
{
nephites.erase(nephites.begin() + (rN));
}
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...