-
writing to file
My program is suppose to search a file for a deleted record, and depending where/if it finds one, it writes output to the file. My code:
Code:
int main()
{
fstream inFile;
int choice = 0;
string blank;
cout << "Enter your choice: " << endl;
cout << "1) Append a record " << endl;
cout << "2) Delete a record " << endl;
cout << "3) Display all records " << endl;
cout << "Enter 1 2 or 3 " << endl;
cin >> choice;
cout << endl;
Person person1;
//Append a record.
if(choice == 1)
{
char status = '!';
inFile.open("DeleteAppend.txt");
//Find deleted record.
while(status != '*')
{
inFile >> status;
if(inFile.fail()) break;
//skip line if record is not deleted
if(status != '*')
{
getline(inFile, blank);
}
}
inFile.close();
inFile.open("DeleteAppend.txt", ios::app);
inFile << "Test";
}
}
My input/ouput file.
Code:
! Will Smith 25 Place Tulsa OK 38135
! Corey Black Elm Street Dallas TX 89148
* Tanner Hall Mount View Denver CO 52742
! Matthew Robins Parkway Chicago IL 91234
The "*" signifies a deleted record. So, when my program finds this, it will insert the new record here. This currently works. I did simplify it here (so it's easier to read), so it just appends to the end of the file. The problem is, if there is no deleted record (no "*" in the file), no output will be written. So, if there is a deleted record, it will append. If there is not a deleted record, nothing happens. With this code, "Test" should be appended in both cases. The only difference i see between finding a deleted record or not is inFile.fail(). Maybe this has something to do with it?
(I can post the whole program if needed.)
Thanks.
-
>The only difference i see between finding a deleted record or not is inFile.fail(). Maybe this has something to do with it?
It could be. Closing and reopening inFile is supposed to clear the flags, but it's possible this isn't happening. Try adding an inFile.clear(); within the if (inFile.fail) statement, and see if this fixes the problem.
-