Hi!
I'm writing a POS system (just for fun) and I have the prompt asking the cashier to input their customer number, and it should check the txt file for that number and read that line into several different variables.
EXAMPLE members.txt
2002 John Adams Q
5565 Quincy Gates L
One simple way would be to read your entire file once and store all the data into memory.
When the user inputs his number, you just have to look for it in the loaded data.
If you really want to search into your file, the code may be something like this
int num;
std::string fname, lname, initial;
// read while you haven't reached the end of the file and memberNumber has not been found
do{
memfile >> num >> fname >> lname >> initial;
}while( memfile.good() && num != memberNumber );
if( memfile.fail() || num != memberNumber )
{
// the number was not found, handle the case
}
else
{
memberNumber = num;
firstName = fname;
lastName = lname;
middleInitial = initial;
}
// if you want to keep the stream open between searches, clear the error flags and reposition it to the beginning of the file
memfile.clear();
memfile.seekg(0, ios::beg);
If you want your code to be cryptic, you can write the do/while loop this way:
while( memfile >> num >> fname >> lname>> initial && num != memberNumber ) {;}
That works, except that it tells me that "error: no match for 'operator!=' in 'num != memberNumber'|
error: no match for 'operator!=' in 'num != memberNumber'|
||=== Build finished: 2 errors, 0 warnings ===|
"
when I compile. Any ideas?
@Hucaru : when are you reading from memfile ?
And you have to check the validity of the stream after you've read from it and before you store the data, or your last acquired value could be garbage.
It's simple : the stream can only report a failure after it happened.
The problem with your loop is that you read data, which can cause a failure, and store it immediatly without checking the stream before.
If ever one of the reads causes an error, the acquired value is very likely to be garbage. With your code, you would store this value into your vector and stop the loop only at the next iteration.
To avoid that, you must:
1) read from the stream into temporary variables
2) check the validity of the stream
3) if the stream is valid, store/use the acquired data.