Here is the exercise:

fileWord

Write the definition of a function named fileWord that receives a string argument that is the name of a file containing words.

The first time the function is called, it returns the first word of the file whose name it was passed. The second time the function is called, it returns the second, word of the file whose name it was passed (which could be a different file than was passed the first time). The third time, it returns the third word in the file whose name it was just passed, and so on.

My assumption it requires static variable that would remember how many times function was called.
This is what I came up with, but on second call (according to codelab) it returns wrong value.
Appreciate any advice.

string fileWord (string file) {
    static int n=1;
    string word;
    ifstream openFile (file.c_str());
    for (int i=0; i<n; i++)
        openFile>>word;
    return word;
    openFile.close();
    n++;
}

Recommended Answers

All 3 Replies

Your function returns on line 7. However, n isn't incremented until line 9, which will never be exectued (since the function will have returned by this point).

Move the n++; line before the return word; line.

Or better, move the return statement to end of the function so that the .close() will be executed as well.

got it. thanx! i did not understand fully how return works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.