0

So i've looked around on this site but nothing seems to work. Im trying to pass an array pointer to a function, read lines of numbers as strings to the array from a text file, then return the array back to the main function. It prints fine in the GetFile method, but once its sent to the main it doesn't appear.

using namespace std;

void GetFile(string *asArray)
{  

ifstream myfile("MyResourceFolder/GolfScores.txt");
int arrayIndex = 0;
string line;
asArray[20];
if (myfile)
{
    while(!myfile.eof())
    {
        getline(myfile, line);
        asArray[arrayIndex] = line;
    }
    myfile.close();
}
}

int main()
{
string aArray[20];
string *p = aArray;
GetFile(p);
cout << aArray[2] << endl;

return 0;
}

1 Answer 1

1

It looks like you neglected to increment your index inside the while loop, resulting in each line being assigned in turn to element 0 in the array, with the last assignment likely being an empty line. Try this instead:

asArray[arrayIndex++] = line;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.