1,105,214 Community Members

static variable

Member Avatar
marnun
Light Poster
28 posts since Dec 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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++;
}
Member Avatar
ravenous
Practically a Master Poster
682 posts since Jul 2005
Reputation Points: 251 [?]
Q&As Helped to Solve: 112 [?]
Skill Endorsements: 13 [?]
 
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.

Member Avatar
vmanes
Postaholic
2,136 posts since Aug 2007
Reputation Points: 1,165 [?]
Q&As Helped to Solve: 282 [?]
Skill Endorsements: 10 [?]
 
2
 

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

Member Avatar
marnun
Light Poster
28 posts since Dec 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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: