madaniloff
madaniloff

Reputation: 57

How to create random name generator from input files c++

I have two text files, firstnames.txt and lastnames.txt. There are 20 names in each, and they are all on a new line. I need to make a random name generator in my program.

I'm not allowed to use string[] so I have to use char*[]. So far, my plan is to add all of the names into the char*[] array, and then make a random number between 1 and 20 and get that index to get a random name. I'm stuck on how to get the names from the text file into a char*[].

Here's what I have so far:

int a = 0;
//Open first name file
ifstream fnameFile;
fnameFile.open("firstnames.txt");
char* fname[20];
//Put names from file into char*[] array
while (fnameFile.good()) {
    getline(fnameFile, fname[a]);
    a++;
}

The getline() doesn't work with the char*[] array though, so how do I get these names into the array?

Upvotes: 2

Views: 1522

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596592

std::getline() only works with std::basic_string types, like std::string.

std::istream::getline() works with char*. You are just not allocating any memory for the char* to point at.

You can use a char[][] instead of a char*[] (a char[] decays into a char*), eg:

const int max_name = ...; // some limit you decide
//Open first name file
ifstream fnameFile("firstnames.txt");
char fname[20][max_name];
//Put names from file into char[][] array
int a = 0;
while ((a < 20) && fnameFile.getline(fname[a], max_name)) {
    ++a;
}

If you absolutely need to use char*[], then you need to allocate memory for each char*, eg:

const int max_name = ...;
//Open first name file
ifstream fnameFile("firstnames.txt");
char* fname[20];
//Put names from file into char*[] array
int a = 0;
while (a < 20) {
    fname[a] = new char[max_name];
    if (!fnameFile.getline(fname[a], max_name)) {
        delete[] fname[a];
        break;
    }
    ++a;
}
...
for (int i = 0; i < a; ++i) {
    delete[] fname[a];
}

Upvotes: 3

Related Questions