Basic C++ Program Help

I'm in a C++ course, and am having a few problems with a problem we were given.

We were given a text file, on the first line are X and Y coordinates of an "emergency" as doubles.
Follow that, each line represents a station, starting with it's ID# as an integer, then it's own X and Y coordinates as doubles.

I initially had a problem with reading information in to the vectors... push_back to save the day. But now I have a new problem. It's a simple "for loop" but I'm getting a bus error.


1
2
3
4
5
	for(int k=0; k < num_stations; k++)
	{
		cout << "Point D";
		cout << station_num[k] <<  x[k] << y[k];
	}

As far as I can tell num_stations is defined fine (I outputted it just before the loop, and it worked fine). I don't see "Point D" displayed.. so obviously it's something with the loop itself.
Last edited on
Without seeing more of your code it's hard to say. Could you post the error message you're getting?
Last edited on

The code is:
1
2
3
4
5
6
7
cout << "Point C" << endl;
	cout << num_stations << endl;
	for(int k=0; k < num_stations; k++)
	{
		cout << "Point D";
		cout << station_num[k] <<  x[k] << y[k];
	}



I'm receiving
"
Point C
6
Bus error
"

The code in it's entirety is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

void read_emergency(double& emergency_x, double& emergency_y);
/*Reads the location of the emergency from the first line of the file.
 */
 
int read_stations(vector<int> station_num, vector<double> x, vector<double> y);
/*Reads the station number (station_num) as well as it's x and y coordinates (vectors x and y respectively)
 *and stores them in to variables.
 *Returns the total number of stations read.
 */
 
void dispatch(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_stations);
/*Tests the distance of all available stations and the emergency, calling display to display the information
 *of the station with the shortest distance to the emergency.
 */

void display(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_station, double distance);
/*Displays the station number and location as well as that stations distance from the emergency, followed by the location of the
 *emergency itself.
 */

double get_distance(double emergency_x, double emergency_y, const vector<int> station_num, const vector<double> x, const vector<double> y, int station);
/*Uses the Pythagorean Theorem to find the distance from an emergency to a given station.
 *Returns the distance as a double.
 */

int main(void)
{
	int num_stations;					// Total number of stations
	double emergency_x, emergency_y;	// X and Y coordinates emergency call 
	vector<int> station_num;			// vector that will hold stations’ ids 
	vector<double> x;					// vector that will hold stations’ Xs 
	vector<double> y;					// vector that will hold stations’Ys 

	read_emergency(emergency_x, emergency_y); // Reads the location of the emergency
	num_stations = read_stations(station_num, x, y); // Reads location of available stations and places the information in vectors.
	cout << "Point C" << endl;
	cout << num_stations << endl;
	for(int k=0; k < num_stations; k++)
	{
		cout << "Point D";
		cout << station_num[k] <<  x[k] << y[k];
	}

	dispatch(emergency_x, emergency_y, station_num, x, y, num_stations); // Calculates which station to dispatch and displays the result
    return 0;
}

void read_emergency(double& emergency_x, double& emergency_y)	
{
	cin >> emergency_x >> emergency_y;
}

int read_stations(vector<int> station_num, vector<double> x, vector<double> y)
{
	int i = 0;
	int id_temp;
	double x_temp, y_temp;
	do
	{
		cin >> id_temp >> x_temp >> y_temp;
		if(!cin.fail())
		{			
			station_num.push_back(id_temp);
			x.push_back(x_temp);
			y.push_back(y_temp);
			
			cout << station_num[i] << " " << x[i] << " " << y[i] << " " << i << endl;
			i++;
			cout << "Point A" << endl;
		}
		else if (cin.fail() || cin.eof())
			break;
	}while(1);
	cout << " Point B" << endl;
	return i;
}

void dispatch(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_station)
{
	int j = 1;
	double distance;
	double test;
	
	distance = get_distance(emergency_x, emergency_y, station_num, x, y, 0);
	
	while(1)
	{
		test = get_distance(emergency_x, emergency_y, station_num, x, y, j);
		
		if (test < distance)
			distance = test;
			
		if (j<num_station)
			j++;
			
		else
			break;
	}
	display (emergency_x, emergency_y, station_num, x, y, j, distance);
}

void display(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_station, double distance)
{
	cout << "Closest station is: " << station_num[num_station] << endl << endl;
	cout << "Its X and Y coordinates are: " << x[num_station] << ", " << y[num_station] << " " << endl << endl;
	cout << "Its distance from the emergency position is: " << distance << endl << endl;
	cout << "The X and Y coordinates of the emergency position are: " << emergency_x << ", " << emergency_y;
}

double get_distance(double emergency_x, double emergency_y, const vector<int> station_num, const vector<double> x, const vector<double> y, int station)
{
	double distance;
	
	distance  = sqrt(pow((emergency_x - x[station]), 2) + pow((emergency_y - y[station]), 2));
	
	return distance;
}

Last edited on
The error your getting is caused by attempting to access too far into the vectors you're using. (That causes the vector to fail an assertion.) There are a variety of errors in various locations that are causing this problem.

First of all, your read stations function is attempting to modify the station_num, x, and y, but is failing to do so because you're passing copies of the vectors, rather than the vectors themselves. You need to pass the vectors to that function by reference.

Second, have you noticed that your do-while loop in the read_stations function is infinite? The same is true of the while loop in your dispatch function. That needs to be fixed.

Another thing I would note that may potentially cause you problems is that the j variable you are using in the dispatch function is set equal to 1. That means that you never access the first station created. (Remember: Vector indexes begin at zero.)

I have one final comment, and please don't take it the wrong way. You are making this program FAR more complicated than it needs to be. C++ is an object oriented language. Why not just create classes to describe the stations, the emergency, and the handler? For example, below is something I wrote up. I think it's a little easier to understand and use. Plus it could be easily modified to assign a given number of vehicles to each station, track how many are out, and re-route from the next closest station. (I'll leave that to you, if you so desire.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;


//This integer acts as a counter for the number of stations created.
int number=1;

class station
{
      public:
             station(double a,double b);
             double getx(){return x;}
             double gety(){return y;}
             int getstationnumber(){return stationnumber;}
      private:
              double x;
              double y;
              int stationnumber;
              station * point;
};

//The ptrvector stores pointers to each station you create. 
//(This would even allow for dynamic station creation if you ever wanted to go that route.)
vector<station*> ptrvector;

//The station constructor just sets the x and y coordinates of the station,
// passes a pointer to itself to the ptrvector for storage, and increments the counter of the station number.
station::station(double a,double b)
             {
               x=a;
               y=b;
               point=this;
               ptrvector.push_back(point);
               stationnumber=number;
               number++;
             }

//the emergency class is as simple as they come. It just assigns the x and y coordinates of the emergency.
class emergency
{
      public:
             emergency(double a,double b)
             {
                x=a;
                y=b;
             }
             double getx(){return x;}
             double gety(){return y;}
      private:
              double x;
              double y;
};

//The IncidentHandler is probably the most complicated part of the whole thing.  One handler needs to be created
//for every emergency (although it could be modified to handle multiple emergencies.)  It just accepts a reference
//to the emergency, and then calls the Find_Closest_station() and dispatch_vehicle() functions to automatically
//handle the emergency.
class IncidentHandler
{
      public:
             IncidentHandler(emergency & accident)
             :theproblem(accident)
             {
		Find_Closest_station();
		dispatch_vehicle();
	     }
             void Find_Closest_station();
             void dispatch_vehicle();
      private:
              emergency theproblem;
              int closeststation;
              double distancetostation;
};

//This is pretty self-explanitory
void IncidentHandler::Find_Closest_station()
{
     //I just used a max distance so it has an initial comparison. Plus it makes sense:Any emergency station will
     //have a limited area that they can cover. There are other ways...
    //distance should be set to the biggest distance covered by the system (before it's someone else's jurisdiction)
    int maxdistance =100;
    for(int i =0; i<ptrvector.size(); i++)
    {
            int temp;
            temp = sqrt(pow((theproblem.getx()-ptrvector[i]->getx()),2)+pow((theproblem.gety()-ptrvector[i]->gety()),2));
            if (temp<maxdistance)
            {
              maxdistance = temp;
              closeststation = ptrvector[i]->getstationnumber();
              distancetostation = temp;
            }
    }
}

//Self explanatory
void IncidentHandler::dispatch_vehicle()
{
     cout<<"The closest station is station "<<closeststation<<" at distance of "<<distancetostation<<" miles"<<endl;
     cout<<"Vehicle dispatched to "<<theproblem.getx()<<","<<theproblem.gety();
}
              
            
    

int main()
{
    station mystation(2,3);
    station mystation2(15,15);
    emergency accident(14,14);
    IncidentHandler Handler(accident);
    cout<<endl;
    system("pause");
}


I hope this helps.

Not taken the wrong way at all. The only reason is that our proff hasn't covered objects yet, and were only supposed to use what he taught us. Silly, I know.


I appreciate the help, and as for the do-while loops, they're not infinite because of the break, but thanks for pointing on the 'j'. I hadn't gotten that far as I've reached this stumbling block I'm at with the BUS Error. Will try it out and get back to you.
You're teacher taught you references and vectors before classes? OKAY...that seems like a pretty backward way to learn it, but then I just taught myself from books, so I'm not really sure what the norm is for learning it in school.

Anyway, your loops are infinite because they'll never make it to that break statement. Not the way you have is set up now anyway. If your planning on having it read from another file, and then execute the break at the end of the file, then that may work. You'll need to make some modifications to get to that point though. For instance, you don't even have <fstream> included...
Last edited on
Here's some quick modifications to your code that fix the error and make it run as it currently stands.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

void read_emergency(double& emergency_x, double& emergency_y);
/*Reads the location of the emergency from the first line of the file.
 */
 
int read_stations(vector<int> & station_num, vector<double> & x, vector<double> & y);
/*Reads the station number (station_num) as well as it's x and y coordinates (vectors x and y respectively)
nd stores them in to variables.
 *Returns the total number of stations read.
 */
 
void dispatch(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_stations);
/*Tests the distance of all available stations and the emergency, calling display to display the information
f the station with the shortest distance to the emergency.
 */

void display(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_station, double distance);
/*Displays the station number and location as well as that stations distance from the emergency, followed by the location of the
mergency itself.
 */

double get_distance(double emergency_x, double emergency_y, const vector<int> station_num, const vector<double> x, const vector<double> y, int station);
/*Uses the Pythagorean Theorem to find the distance from an emergency to a given station.
eturns the distance as a double.
 */

int main(void)
{
	int num_stations;					// Total number of stations
	double emergency_x, emergency_y;	// X and Y coordinates emergency call 
	vector<int> station_num;			// vector that will hold stations’ ids 
	vector<double> x;					// vector that will hold stations’ Xs 
	vector<double> y;					// vector that will hold stations’Ys 
	read_emergency(emergency_x, emergency_y); // Reads the location of the emergency
	num_stations = read_stations(station_num, x, y); // Reads location of available stations and places the information in vectors.
	cout << "Point C" << endl;
	cout << num_stations << endl;
	cout<<station_num.size()<<endl;
	cout<<x.size()<<endl;
	cout<<y.size()<<endl;
	for(int k=0; k < num_stations; k++)
	{
		cout << "Point D";
		cout << station_num[k] <<  x[k] << y[k];
	}
	dispatch(emergency_x, emergency_y, station_num, x, y, num_stations); // Calculates which station to dispatch and displays the result
	system("pause");
 //   return 0;
}

void read_emergency(double& emergency_x, double& emergency_y)	
{
	cin >> emergency_x >> emergency_y;
}

int read_stations(vector<int> & station_num, vector<double> & x, vector<double> & y)
{
	int i = 0;
	int id_temp;
	double x_temp, y_temp;
	int count = 2;
	do
	{
		cin >> id_temp >> x_temp >> y_temp;
		if(!cin.fail())
		{			
			station_num.push_back(id_temp);
			x.push_back(x_temp);
			y.push_back(y_temp);
			
			cout << station_num[i] << " " << x[i] << " " << y[i] << " " << i << endl;
			i++;
			cout << "Point A" << endl;
		}
		else if (cin.fail() || cin.eof())
			break;
		count--;
	}while(count);
	cout << " Point B" << endl;
	return i;
}

void dispatch(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_station)
{
	int j = 0;
	double distance;
	double test;
	
	distance = get_distance(emergency_x, emergency_y, station_num, x, y, 0);
	int counter = 1;
	while(counter)
	{
		test = get_distance(emergency_x, emergency_y, station_num, x, y, j);
		
		if (test < distance)
			distance = test;
			
		if (j<num_station)
			j++;
			
		else
			break;
		--counter;
	}
	display (emergency_x, emergency_y, station_num, x, y, j, distance);
}

void display(double emergency_x, double emergency_y, vector<int> station_num, vector<double> x, vector<double> y, int num_station, double distance)
{
	cout << "Closest station is: " << station_num[num_station] << endl << endl;
	cout << "Its X and Y coordinates are: " << x[num_station] << ", " << y[num_station] << " " << endl << endl;
	cout << "Its distance from the emergency position is: " << distance << endl << endl;
	cout << "The X and Y coordinates of the emergency position are: " << emergency_x << ", " << emergency_y;
}

double get_distance(double emergency_x, double emergency_y, const vector<int> station_num, const vector<double> x, const vector<double> y, int station)
{
	double distance;
	
	distance  = sqrt(pow((emergency_x - x[station]), 2) + pow((emergency_y - y[station]), 2));
	
	return distance;
}
Topic archived. No new replies allowed.