Edvinas Perminas
Edvinas Perminas

Reputation: 33

C++ dealing with files

I have a problem working in C++ with txt files.. First of all, I want to make a program which have .cpp and .h files.. which have classes and functions.

So here is my problem:

for example, i have txt file which contains 5 lines of text (players names). So I want to make every line of that txt to be a variable of string.. But as long as I want to use that new variables they suddently disappears.

Here is program code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string line;
    int i;
    string player[5];

    ifstream myfile ("1-Efes Pilsen.txt");

    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            for (i=0;i<5;i++)
            {
                getline (myfile,line);
                player[i] = line;
            }
            // after this point I still can use new variables
        }
    }
    else cout << "Unable to open file"; 

    cout << player[1]; // <--- NOT WORKING. WHY?

    myfile.close();   
}

Upvotes: 0

Views: 197

Answers (1)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422222

While it is not clear to me how it's not working, I can guess that there are more contents in the file than just 5 strings (perhaps another newline) which causes the while condition to evaluate to true causing the for loop to read 5 lines (which will fail and not actually read anything) and replace the good values in the string array with crappy ones (empty string).

Instead of having an outer while loop, you probably want to add the condition to the for loop itself; something along the lines of:

for (i=0;i<5 && myfile.good();i++)
{
   getline (myfile,line);
   player[i] = line;
}

Upvotes: 3

Related Questions