We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,031 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

static variable

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++;
}
3
Contributors
3
Replies
28 Minutes
Discussion Span
5 Months Ago
Last Updated
5
Views
Question
Answered
marnun
Light Poster
28 posts since Dec 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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.

ravenous
Practically a Master Poster
681 posts since Jul 2005
Reputation Points: 286
Solved Threads: 111
Skill Endorsements: 9

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

vmanes
Postaholic
2,015 posts since Aug 2007
Reputation Points: 1,283
Solved Threads: 242
Skill Endorsements: 6

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

marnun
Light Poster
28 posts since Dec 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 5 Months Ago by ravenous and vmanes

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0909 seconds using 2.79MB