Reading a file one line at a time using a function, but I can't get past the first line

So in my assignment I have a .txt file from which I have to read from it one line at a time and do some stuff with those values. I'm using a while loop to call the function, but every time it starts from the beginning of the file, so I just end up reading the first line a million times.
here's the while loop:
1
2
3
4
  while (ReadTime(hr, min, elap) != 0 )
{
elap = ReadTime(hr, min, elap);
}


and here's the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ifstream infile;
infile.open("time-elapsed.txt");
infile>>hour>>minute>>elapsed;

cout << hour << ":"<<minute<<"\tElapsed: "<<elapsed<<endl;  

if ((hour =0) && (minute=hour) && (elapsed=hour))
{
cout << "\nKILL";
return 0;
}
else 
{
cout << "\nRUN";
return elapsed;
}
}


dont mind the "RUN" and "KILL" thats just some testing and troubleshooting I was doing.
Last edited on
That would be because you are creating a new stream each time. You could always pass the stream to the function. Also you are calling the function twice so that would mean if it worked properly you would have different results for the check in the while loop and the assignment

1
2
3
4
5
6
7
ifstream infile;
infile.open( "time-elapsed.txt" );

while ( elap = (ReadTime(hr, min, elap , infile) ) //read while elap does not equal 0
{
    cout << "elap = " << elap << " which is not 0" << endl;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int ReadTime( int &hour , int &min , int &elap , ifstream &infile )
{
    infile>>hour>>minute>>elapsed;

    cout << hour << ":"<<minute<<"\tElapsed: "<<elapsed<<endl;  

    if ((hour ==0) && (minute==hour) && (elapsed==hour))
    {
        cout << "\nKILL";
        return 0;
    }
    else 
    {
        cout << "\nRUN";
        return elapsed;
    }
}


*typo
Last edited on
I get an error on line 4 in main

"undefined refrence to 'ReadTime(int&, int&, int, std::basic_ifstream<char, std::char_traits<char>>&)"
Show me your prototype/definition of the function.
definition

 
int ReadTime(int&, int&, int, ifstream&);


prototype
 
int ReadTime( int hour , int minute , int elapsed , ifstream &infile )

@motez23

Did you mean to use an assignment operator here:

if ((hour =0) && (minute=hour) && (elapsed=hour))

The equality operator is ==

HTH
Honestly I would pass all 3 of the ints as reference and then return success or fail. Then in the while loop output the read info: cout << hour << ":"<<minute<<"\tElapsed: "<<elapsed<<endl;

Also make sure that the prototype and definitions match.
unfortunately I can't do that. And wouldn't it still read the file from the beginning each time the function is called?
No because it will continue from where the stream left off ( if you pass it by reference ). You can't use the variables as references? Why pass them to the function then you are just using them to read into to/temp variables.
Topic archived. No new replies allowed.