I have an assignment in class that asked me to write and unknown number of records(but less than 20) to a file and read it back and display it.
i got this to work but i get end up displaying the last entry twice. i was wondering if there was a better way to fix this. and just so you i have already turn the assignment in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
its was originally:
for(int i = 0; i<20 && !infile.eof();i++)
{
// get info from file here
// displace with cout statment here
}
my solution:
// get info from file here
for(int i = 0; i<20 && !infile.eof();i++)
{
// displace with cout statment here
// get info from file here
}
like i said, is there a better way to handle this?
no overloaded operator but i do know what you are getting at. this assignment isn't using object though.
does the first example where "(infile >> myrecord)" act as a bool and if there is a value then run the loop? will this still work for "(infile >> fname >> lname >> age)?
The if (infile >> whatever) is the same as if ((infile >> whatever).good()). (Remember that operator>> returns the istream and if (infile) is the same as if (infile.good()).
Read one thing at a time. If the user does not type "end", then read the MI, Surname, Number.
Personally, I can't stand magic words in input. I don't remember where I read this, but I seem to recall that a military computer system was broken because the programmer used the name "Donald Duck" as a hard-coded test case in the GI software. Problem was, some people actually are named Donald Duck -- including one poor fellow who enlisted.
It is better to enter nothing if you are done. Read one line of input at a time. If it is empty, then your user is done. If not, use a std::stringstream to get it into your variables.
1 2 3 4 5 6 7 8 9 10 11 12 13
string s;
for (int i = 0; i < 20; i++)
{
cout << "Enter info (or enter nothing to stop): " << flush;
getline( cin, s );
if (s.empty()) break; // user is done
istringstream ss( s );
ss >> firstname >> middleinitial >> surname >> number;
if (ss.fail()) fooey();
outfile << ... << endl;
}
You've got two variables named "line", one (a std::string) on line 11 and another (a std::istringstream) on line 22. Get rid of the one on line 11 and it should work for you.
Also, that cast to 'int' on line 23 looks suspicious. Why are you doing that? (Your variable is already an 'unsigned long'.)