Problem with while loop

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?
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.
int reader (int a)
{
ifstream data;
data.open ("Data.txt");
int x;
while (a > 0)
{
data >> x;
a--;
}
return (x);
}
Thanks. I should not have made such a stupid mistake
Topic archived. No new replies allowed.