[p] So I've been working on some code that will read the data off a file, which looks like:
2 apple
1 house 0 3 0
1 shed 0 4 0
3 car
1 city 4 5 1
1 town 3 4 1
4 t j johnson
Now the file is bigger then this so will put the rest in if needed. but it goes in this order of sequence.
I have code that can take the file out as a string but that means i cant touch the ints in there. so i have been working on using a vector to take each item out and store it through 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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
class info{
public:
info(int t, string p, int pr, int r, int g);//overload
int gettype();
string getName();
int getnum1();
int getnum2();
int getnum3();
void setType(int t);
void setname(string p);
void setnum1(int r);
void setnum2(int pr);
void setnum3(int g);
private:
int type;
string name;
int num1;
int num2;
int num3;
};
bool getfilecontent(std::string Text, vector<info>& newinfo)
{
std::ifstream in(Text.c_str());//read in file and fill vector
if (!in)
{
cerr << "cannot open file" << endl;
return false;
}
int ntype = 0;
std::string str;
int pri = 0;
int nr = 0;
int ng = 0;
string a;
while (in >> ntype>>a>> str>> pri>> nr>> ng)
{
for (int x = 0; x < 26; x++)
{
info Newinfom(
ntype, str, pri, nr, ng);
newinfo.push_back(Newinfom);
int i = 0;
cout << Newinfo[i].getname() << endl;
i++;
}
}
in.close();
return true;
void printv(vector<info>&Newinfo);
int main() {
vector<info> myinfo;
bool result = getfilecontent("Text.txt", myinfo);
if (result)
{
std::cout << "The board has been loaded successfully - you are now able to play:" << std::endl;
}
printv(myinfo);
system("pause");
}
void printv(vector<info>&newinfo) {
int size = 26;
for (int i = 0; i < size; i++) {
cout << newinfo.at(i).getname();
//Unhandled exception at 0x743418A2 in Project9.exe: Microsoft C++ exception: //std::out_of_range at memory location 0x007BF658. happens here
}
}
|
Correct me if im wrong but is this error because the first line only has an int and a string ?
My question is, is it possible to read the first int and decide whats on that line and how to read it.
i.e.
sees that first int is 2 and knows there is only an int and a string and reads them. then sees the first int second row is 1 and then knows that there is another 3 ints to read. and then the last one with 3 strings.
i dont want to be writing code for each line just what to do if it sees certain ints at the start.
if you need anything else just tell me and ill get back.
also haven't but the class functions in as i believe that i have got them correct.
thank you![p]