Home > Net >  ifstream unable to load in two or more files correctly [C ]
ifstream unable to load in two or more files correctly [C ]

Time:10-28

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:

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...

CodePudding user response:

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.

  • Related