Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ifstream unable to load in two or more files correctly [C++]

I’m making an "Identity generator" where the computer randomly picks lines from .txt files.

Although it works fine with the first part of the code, when I repeat that code and change the variables it still uses the old txt file.

Expected result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Full name: {random first name} {random sur name}
Address: {random address}

Actual result:

Full name: {random first name} {random first name}
Address: {random first name}

My code

    cout << "Full name: ";

    srand((unsigned) time(NULL)); 
    std::ifstream firstnamefile("englishfirstname.txt");
    int total_lines = 0;
    while(getline(firstnamefile,line))
    {
        total_lines++; 
        lines.push_back(line);  
    }
    int random_number = rand() % total_lines;
    cout << lines[random_number] << " ";

    //--- Surname ---

    srand((unsigned) time(NULL)); 
    std::ifstream surnamefile("englishsurname.txt");
    total_lines = 0;
    while(getline(surnamefile,line))
    {
        total_lines++; 
        lines.push_back(line);  
    }
    random_number = rand() % total_lines;
    cout << lines[random_number] << endl;

    // --- Address ---

    cout << "Address: ";
    
    srand((unsigned) time(NULL)); 
    std::ifstream addressfile("addresses.txt");
    total_lines = 0;
    while(getline(addressfile,line))
    {
        total_lines++; 
        lines.push_back(line);  
    }
    random_number = rand() % total_lines;
    cout << lines[random_number] << endl;

The .txt files are just a list of names for example:

John
Michael
Matthew
Etc…

>Solution :

You never clear lines, so the start of the vector is always going to be your list of first names. You do reset total_lines to 0 before reading each file, so your random range is 0..total_lines each time, so you’re always picking from the start of the array, which again, is all first names.

Assuming lines is a std::vector, you need lines.clear() along with setting total_lines to 0 to reset the state between each file read.

Note that you have three identical blobs of code that differ only by a file name; this is a very good candidate for a function that accepts a file as input, and returns a random line as output.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading