creating a vector that contains a string and two int

Hi yall,
So for a practice test, there is a problem that states:
Assume that a vector of Coaster Objects has already been declared and filled with Coaster objects created from the contents of the file:
vector<coaster> rides; // already filled with coaster objects.

It goes on to ask a different question but I was more confused by how he was able to make a vector of type(coaster) that took a string and two integers.

So my question is how do I make a vector that takes in for [i] a string(name of the coaster) and two integers one for wait time and the other for the puke chance and how do I read it in from the text file?

This is the text file:
Coaster.txt
1
2
3
4
5
6
 superman 90 20
 daredevil 120 40
 v2 90 20
 coastetocoaster 30 10
 kong 60 30
 medusa 90 30 


And this is as far as I got:
1
2
3
4
5
  ifstream data;
  data.open("coaster.txt");
  string n;
  int w, int p;
  vector<coaster>
Last edited on
You can't mix types in a vector.

Luckily, the question isn't asking you to do that. It's asking you to make a vector of Coaster objects. Every single item in that vector is of the same type - Coaster.

You haven't shown us the definition of Coaster, but I assume it's a struct (or a class - in C++, they're the same thing), whose members are a string and two integers.

http://www.cplusplus.com/doc/tutorial/structures/
Last edited on
Yes, coaster is a class!!

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
#include<iostream>
#include<vector>
#include<string>
#include"Random.h"
#include<fstream>

using namespace std;
//header
class Coaster
{
  public:
    string get_name();
    int get_wait();
    void wuss_factor(int additional);
    bool ride_coaster();
    coaster(string n, int w, int p);
  Private:
    string name;
    int wait;
    int puke_percent;
}
//coaster.cpp

Coaster::coaster(string n, int w, int p)
  : name(n), wait(w), puke_percent(p)
{
}

int Coaster::get_wait()
{
  return wait;
}

string Coaster::get_name()
{
  return name;
}

bool Coaster::ride_coaster()
{
  Random r(1,100);
  r.get();
  if(r<=wuss_factor)
  {
    return true;
  }
  else 
  {
    return false;
  }
}

void Coaster::wuss_factor(int additional)
{
  puke_percent += additional;
}


but still, how do I go about making the vector and reading in the string and integers from the txt file?
If the file contains
superman 90 20


Then you can simply do:
1
2
3
4
5
6
7
8
9
10
11
12
13
ifstream fin("Coaster.txt");

std::string name;
int wait;
int puke;

vector<Coaster> coasters;

whlie (fin >> name >> wait >> puke)
{
    // name, wait, and puke have been filled with values from the file
    coasters.push_back(Coaster(name, wait, puke));
}
Topic archived. No new replies allowed.