Problem with while loop

Jun 3, 2013 at 5:52pm
I wrote this function to find the value of line 'a' in a file
1
2
3
4
5
6
7
8
9
10
11
12
int reader (int a) 
{
int x; 
while (a > 0)   
{
ifstream data;
data.open ("Data.txt");
data >> x;
a--;
}
return (x);
}

The problem is, regardless of what the value of a is, the function always returns the value of the first line. To me it seems like it resets every time the while loop runs. What can I do to correct this?
Jun 3, 2013 at 6:02pm
You're opening the data file and reading the first record each time through the loop. This is going to result in lots of open files and not the result you want.

You want to open the file BEFORE you enter the loop and close the file when you exit the loop.
Jun 3, 2013 at 6:04pm
int reader (int a)
{
ifstream data;
data.open ("Data.txt");
int x;
while (a > 0)
{
data >> x;
a--;
}
return (x);
}
Jun 3, 2013 at 6:10pm
Thanks. I should not have made such a stupid mistake
Topic archived. No new replies allowed.