Read One Value Function

Hey I'm trying to read in one value at a time from a file with this function, but its giving me back junk. I have tried everything I know can somebody help me please??

javascript:tx(
void ReadValue (istream &inF, int & num, bool & success)
{
inF.clear();
inF.seekg(0L, ios::beg);

inF >> num;
cout << num;

}


int main()
{
ifstream inF1;
int num;
bool getNum = 0;
string filename;

cout<<"File Name = ";
cin >> filename;

inF1.open(filename);

ReadValue(inF1, num, getNum);')
I don't really know everything about fstream
but this works for me

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    ifstream inFile;
    int num;
    string filename;

    cout<<"filename : ";
    cin >> filename;

    inFile.open( filename );

    inFile >> num;
    cout << num;

    return 0;
}


Anyway, why would you use clear() ?
from what I read here :

http://www.cplusplus.com/reference/ios/ios/clear/

It sets flag to a stream or something ?
I never used it so I don't really know ( sorry, If I am not helping )


and inF.seekg(0L, ios::beg);
doesn't this reset the stream and set the pointer to the start of the file again...
is that what you want to do ???
Yes, I'm doing this just to make sure that the function is reading from the beginning of the input file. There is another place in my program which uses this same file to get the sum of the values in the file, so I just wanted to make sure that it is reading from the front.

And yes the code you have above works for me too, I don't understand why its not working inside my function though. That's exactly the code I have it should be working.

Thanks a lot for you help though!!!!
Wasn't that meant to be something like success = inF >> num;? Otherwise that output parameter is left unused.
Either way, works for me, after adding the missing #includes
Last edited on
Perhaps check the success of inF1.open(), instead of just calling ios::clear() regardless.

Calling ios::clear() resets your streams internal error flags, but if there was a genuine problem with opening the stream in the first place, then you're just ignoring it and whatever you read from such an invalid stream is likely to be junk.
Topic archived. No new replies allowed.