Graduation Program

http://www.cplusplus.com/articles/N6vU7k9E/
So I've been working through this program. Been getting it set up and ready to go all day. I have a file with a bunch of different names for the bunnies, I'm just not sure how to get a specific line, or more of a random line from my file. Let's say I have one name per line, with 40 names, is there a function I can use to get a specific line, defined by a random number? I guess I'll also need a way to get the number of lines before hand, so I dont generate a random number that would be eof
I have a file with a bunch of different names for the bunnies, I'm just not sure how to get a specific line, or more of a random line from my file.

You could read the whole file, placing each name into a vector. So, after reading a file with 40 names, you should have a vector with 40 names in it (you could use std::strings). You can limit your random number to the possible indexes into your vector.
That would make more sense. So just read into the vector until I hit eof? Then pick a random name from the vector?
Yep, that's how I would do it. If your file doesn't change and it's of reasonable size then I would say that's the best approach.
Yea the file doesnt change during run time. It probably will never change again actually.
Last edited on
Ok, well right now I have this being done in my class, I feel like thats bad though. It means everytime a new object is made, this file is gonna be opened up, read into a vector, and closed. But I'm not sure where else to put this.
Ok I'm actually lost as to how to do this.

1
2
3
4
5
while(nameFile.eof() == false)
	{
		nameFile.getline(names[index] , 1000);
		index++;
	}


This doesnt work
There's a separate getline function for std::strings. Sadly, those libraries aren't as tightly-integrated as they could be.
http://www.cplusplus.com/reference/string/getline/

Also, might I suggest using the push_back() function for adding those strings to your vector?
http://www.cplusplus.com/reference/stl/vector/push_back/

-Albatross
Ooh push_back() would be much better.
Now how I read one line into one element, the next line into next element, and so on. Not sure how to go about changing lines with this
As Albatross showed, you can use std::getline to get one line from the file and you can use push_back to place that line into the vector.

e.g.

1
2
3
4
5
6
7
8
9
10
using namespace std;

string nameFromFile;
vector<string> namesVector;

while(!nameFile.eof())
{
    getline( nameFile, nameFromFile );
    namesVector.push_back( nameFromFile );
}
And that one would move down a line each iteration?
Yes, getline moves the file pointer down to the next line.
:O Alright cool! Thanks you two. This is probably the most fstream work I've done, so I haven't been so sure on how it works
Topic archived. No new replies allowed.