I'm trying to make a random name generator. The problem is that in order to get the count of lines in the file, I have to loop through it.
So when I need to loop through it again in getRandomName() to get a name, it has already reached the end of the file
I tried solving the issue with seekg(0, std::ios::beg) but it doesn't work for some reason.
int getLineCount(std::fstream &names) {
int count{};
while (names) {
std::string name;
getline(names, name);
++count;
};
// last line is empty
return count - 1;
}
std::string getRandomName(std::fstream &names, int lineCount) {
int randomNum{getRandomNumber(1, lineCount)};
std::string name;
names.seekg(1, std::ios::beg); // here i try to go to the beginning but it doesnt work
for (int i{0}; i < randomNum; ++i) {
names >> name;
};
return name;
};
int main() {
std::srand(static_cast<unsigned int>(std::time(nullptr)));
std::rand();
std::fstream names{"names.txt"};
int lineCount{getLineCount(names)};
std::cout << getRandomName(names, lineCount);
}