1.11M Members

static variable

 
0
 

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++;
}
 
1
 

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.

 
2
 

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

 
0
 

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

Question Answered as of 1 Year Ago by ravenous and vmanes
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: