How to open and close a file from a while - c++

I need this program to show the count of words from a file (text document). However, not reseting counter of words. its supposed to be 7 but it is displaying 62 words. I was told to close the file from the second last while and create a new while (which is the last one) and open the file again. I've working on this for a while. However, after making the changes it doesn't display the file anymore. the only thing display in the screen it s a th and account of 2 words.
Thanks for your help
#include<iostream>
#include<fstream>//step#1
#include<string>
using namespace std;
int main()
{
string word,fileName;
char character;
int charcounter = 0, wordcounter = 0;
ifstream inData;// incoming file stream variable
cout << " Enter filename or type quit to exit: ";
cin >> fileName;
//loop to allow for multiple files data reads
while (fileName != "quit")
{
inData.open(fileName.c_str());//open file and bind file to ifstream variable
//loop for file not found validation
while (!inData)//filestream is in fail state due to no file
{
inData.clear();//clear the fail state
cout <<"File not found. Enter the correct filename: ";
cin >> fileName;
inData.open(fileName.c_str());
}
inData >> character;//extract a single character from the file
cout << "\n*****************************\n";
while (inData)
{
cout << character;
inData.get(character);
charcounter++;
}
cout << "\n******************************\n";
cout << fileName << " has " << charcounter << " words." << endl;
inData.close();//close the ifstream conection to the data file
while (inData)
{
cout << word;
wordcounter++;
inData.open(fileName.c_str());
}
charcounter = 0; //reset character count
wordcounter = 0;
//port for next file or exit
cout << "Enter a filename or type quit to exit: ";
cin >> fileName;
}
return 0;
}

Do you want this?
#include<iostream>
#include<fstream>//step#1
#include<string>
using namespace std;
int main() {
string word,fileName;
char character;
int charcounter = 0, wordcounter = 0;
ifstream inData;// incoming file stream variable
cout << " Enter filename or type quit to exit: ";
cin >> fileName;
//loop to allow for multiple files data reads
while (fileName != "quit")
{
inData.open(fileName.c_str());//open file and bind file to ifstream variable
//loop for file not found validation
while (!inData)//filestream is in fail state due to no file
{
inData.clear();//clear the fail state
cout <<"File not found. Enter the correct filename: ";
cin >> fileName;
inData.open(fileName.c_str());
}
cout << "\n*****************************\n";
while (inData)
{
inData >> character;//extract a single character from the file
cout << character;
charcounter++;
}
cout << "\n******************************\n";
cout << fileName << " has " << charcounter << " chars." << endl;
inData.close();//close the ifstream conection to the data file
inData.open(fileName.c_str());
while (inData)
{
inData >> word;
cout << word;
wordcounter++;
}
cout << "\n******************************\n";
cout << fileName << " has " << wordcounter << " words." << endl;
inData.close();//close the ifstream conection to the data file
charcounter = 0; //reset character count
wordcounter = 0;
//port for next file or exit
cout << "Enter a filename or type quit to exit: ";
cin >> fileName;
}
return 0;
}

Related

Reading in one word from a file

I'm new to C++, and I need to find the one word inputted (searchWord) within the text file "input.txt".
I have it now where it will output every word in the file, but I need it to just output the inputted string and find it.
#include<iomanip>
#include<fstream>
#include<string>
using namespace std;
int main(){
// Variable Declaration
string fileName;
string searchWord;
int exitValue = 0;
// Name the file to open
ifstream inputFile;
// Prompt the user to enter the file name
cout << "Enter the name of the file: ";
cin >> fileName;
// Logic to determine if the file name equals "input.txt"
if (fileName == "input.txt"){ // if user input = input.txt
inputFile.open("input.txt"); // opening input.txt
}
else{
cout << "\nCould not open '" << fileName << "'." << endl;
exit(0);
}
// Prompt the user for a word to search for in the file
cout << "Enter a value to search for: ";
cin >> searchWord;
// Logic to determine if the inputted string is in the file or not
while (inputFile >> searchWord){
cout << "\n'" << searchWord << "' was found in '"
<< fileName << "'." << endl;
}
inputFile.close();
return 0;
}
Do it just a bit different:
// Logic to determine if the inputted string is in the file or not
string inputWord;
while (inputFile >> inputWord){ // Do not overwrite the given searchWord
if(inputWord == searchWord ) { // Check if the input read equals searchWord
cout << "\n'" << searchWord << "' was found in '"
<< fileName << "'." << endl;
break; // End the loop
}
}
This worked for me:
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
// Returns the index of the value you are looking for.
// If the value isn't found, it returns -1.
int searchFile(string filename, string value) {
FILE *fp;
int c, i = 0;
string contents = "";
fp = fopen(filename.c_str(), "r");
while (true) {
c = fgetc(fp);
contents += c;
if (feof(fp)) {
break;
}
i++;
if (i >= value.length() && contents.substr(i - value.length(), i) == value) {
return i;
}
}
fclose(fp);
return -1; // value not found in file
}
int main() {
string fileName;
string value;
cout << "Enter file name: ";
cin >> fileName;
cout << endl << "Enter search value: ";
cin >> value;
int index = searchFile(fileName.c_str(), value.c_str());
if (index == -1) cout << "Not found";
else cout << "Found at index " << index << endl;
cin.get();
cin.get();
return 0;
}

How do I extract specific words from a string in a text file? c++

my assignment is to take a string from a text file and count the number of words in it. I've gotten that far but now we have to be able to take a certain number and display that number word to the console. Say my string is "Hello World" if I enter '2' it should give me the result "World". I'm not really sure how my function should look for this. This is my code so far.
void getFileInfo(ifstream &inFile);
string words(ifstream &inFile);
int numOfWords(ifstream& inFile);
int main() {
ifstream inFile;
string sentence, fileName;
int numCount, word;
getFileInfo(inFile);
numCount = numOfWords(inFile);
inFile.clear(); // resets file pointer from the beginning
inFile.seekg( 0 );
sentence = words(inFile);
cout << sentence << ": has " << numCount << " words in it" << endl;
cout << "Enter a number to extract a word: ";
cin >> word;
}
void getFileInfo(ifstream &inFile){
string fileName;
do{
cout << "Please enter the filename: " << endl;
cin >> fileName;
inFile.open(fileName.c_str());
if(!inFile){
cout << "Invalid try again" << endl;
}
}while(!inFile);
}
string words(ifstream &inFile){
string words, theWords;
getline(inFile, words);
cout << words;
return theWords;
}
int numOfWords(ifstream& inFile){
string fileName, words, str;
int numCount =0;
while(inFile >> words){
++numCount;
}
return numCount;
}
Any suggestions?
Thanks in advance
I would suggest slightly different code for your task. First, write some simple helper functions:
// Clear error flags (EOF, for example) and reset stream to the beginning.
void resetStream(ifstream& stream) {
stream.clear();
stream.seekg(0, ios_base::beg);
}
// Count the words in text file stream.
int getWordsCount(ifstream& stream) {
int count = 0;
while (stream) {
string tmp;
stream >> tmp;
if (!tmp.empty()) ++count;
}
resetStream(stream);
return count;
}
// Read word by specific number.
string getWordByNumber(int number, ifstream& stream) {
string word;
while (number--)
stream >> word;
resetStream(stream);
return word;
}
Now you can easily get the number of words in a file and display a specific word by its number. For example:
int main() {
string fileName;
cout << "Enter the file name: \n";
cin >> fileName;
ifstream stream(fileName);
if (!stream)
cout << "Failed to open file!" << endl;
else {
int totalCount = getWordsCount(stream);
int currentCount = 0;
cout << "Total words count: " << totalCount << "\n\n";
do {
cout << "Enter the word number (enter '0' to finish): ";
cin >> currentCount;
if (currentCount == 0) break;
else if (currentCount > totalCount)
cout << "Invalid value!\n";
else {
string wordByNumber = getWordByNumber(currentCount, stream);
cout << "Word by number: " << "'" << wordByNumber << "'\n";
}
cout << "\n";
}
while (true);
}
return 0;
}
Warning: This code is not very efficient and I have not tested it much. If you have any problems, be sure to write a comment.

I am getting unknown ascii code characters in my program console output

My program basically ask user for inputs and it saves data like login data, username in a text file and uses same file to retrieve data and displays in the output console. When program executes users can choose between options 1 to 6, option 6 is for existing out of the application and rest of the options from 1 to 5 are for users to input data and to view stored data in the file.
When program displays data in the console, I see lots of unnecessary ASCii code. Why is it showing up and how do I make them go ? Thanks!!
int main() {
//Considering the max length of data entered (name) to be 15.
char data[15];
int n = 0, option = 0, count_n = 0;
//This is the initial mark alloted to a subject.
string empty = "00";
string proctor = "";
//Name of the file in which DB is stored.
ifstream f("Example.txt");
string line;
//The following for loop counts the total number of lines in the file.
for (int i = 0; std::getline(f, line); ++i) {
count_n++;
}
while (option != 6) {
//This prints out all the available options in the DB
cout << "\nAvailable operations: \n1. Add New Students\n2."
<< "Student Login\n3. Faculty Login\n4. Proctor Login\n5. Admin View\n"
<< "6. Exit\nEnter option: ";
cin >> option;
if (option == 1) {
cout << "Enter the number of students: ";
cin >> n;
count_n = count_n + n;
for (int i = 0; i < n; i++) {
ofstream outfile;
outfile.open("Example.txt", ios::app);
//The entire data of a single student is stored line-by-line.
cout << "Enter your registration number: ";
cin >> data;
outfile << data << "\t";
cout << "Enter your name: ";
cin >> data;
int len = strlen(data);
while (len < 15) {
data[len] = ' ';
len = len + 1;
}
outfile << data << "\t";
//Inserting empty data initially into the file
outfile << empty << "\t";
outfile << empty << "\t";
cout << "\b \b";
cout << "Enter your proctor ID: ";
cin >> proctor;
outfile << proctor << endl;
}
}
else if (option == 2) {
char regno[9];
cout << "Enter your registration number: ";
cin >> regno;
ifstream infile;
int check = 0;
infile.open("Example.txt", ios::in);
//This loop prints out the data according to the registration number specified.
while (infile >> data) {
if (strcmp(data, regno) == 0) {
cout << "\nRegistration Number: " << data << endl;
infile >> data;
cout << "Name: " << data << endl;
infile >> data;
cout << "CSE1001 mark: " << data << endl;
infile >> data;
cout << "CSE1002 mark: " << data << endl;
infile >> data;
cout << "Proctor ID: " << data << endl;
infile.close();
check = 1;
}
}
if (check == 0) {
cout << "No such registration number found!" << endl;
}
}
//This loop is used to view and add marks to the database of a student.
else if (option == 3) {
char subcode[7];
cout << "Enter your subject code: ";
cin >> subcode;
string code1 = "CSE1001", code2 = "CSE1002", mark = "";
ifstream infile;
int check = 0;
cout << "\nAvailable operations: \n1. Add data about marks\n"
<< "2. View data\nEnter option: ";
cin >> option;
if (option == 1) {
cout << "Warning! You would need to add mark"
<< "details for all the students!" << endl;
for (int i = 0; i < count_n; i++) {
fstream file("Example.txt");
//The seek in file has been done according to the length
//of the data being inserted. It needs to adjusted accordingly
//for diffferent lengths of data.
if (strcmp(subcode, code1.c_str()) == 0) {
file.seekp(26 + 37 * i, std::ios_base::beg);
cout << "Enter the mark of student#" << (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
if (strcmp(subcode, code2.c_str()) == 0) {
file.seekp(29 + 37 * i, std::ios_base::beg);
cout << "Enter the mark of student#" << (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
}
}
//This loop is used to view marks of a student.
//The extra infile commands have been used to get a specific mark
//only since the data has been seperated by a tabspace.
else if (option == 2) {
infile.open("Example.txt", ios::in);
if (strcmp(subcode, code1.c_str()) == 0) {
cout << "Registration number - Marks\n" << endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
infile >> data;
check = 1;
}
}
infile.close();
infile.open("Example.txt", ios::in);
if (strcmp(subcode, code2.c_str()) == 0) {
cout << "Registration number - Marks\n" << endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
check = 1;
}
}
}
infile.close();
if (check == 0) {
cout << "No such subject code found!" << endl;
}
}
//This loop displays all the details of students under the same proctor ID.
else if (option == 4) {
char procid[7];
cout << "Enter your proctor ID: ";
cin >> procid;
int check = 1;
char temp1[100], temp2[100], temp3[100];
char temp4[100], id[100];
ifstream infile;
infile.open("Example.txt", ios::in);
while (infile >> temp1) {
infile >> temp2;
infile >> temp3;
infile >> temp4;
infile >> id;
if (strcmp(id, procid) == 0) {
cout << "\nRegistration Number: " << temp1 << endl;
cout << "Name: " << temp2 << endl;
cout << "CSE1001 Mark: " << temp3 << endl;
cout << "CSE1002 Mark: " << temp4 << endl;
check = 1;
}
}
if (check == 0) {
cout << "No such proctor ID found!" << endl;
}
}
//This loop acts as an admin view to see all the data in the file.
else if (option == 5) {
char password[25];
cout << "Enter the admin password: ";
cin >> password;
//This variable value can be changed according to your requirement
//of the administrator password.
string admin_pass = "admin";
if (strcmp(password, admin_pass.c_str()) == 0) {
cout << "Reg No. \tName\tCSE1001\tCSE1002\tProctor ID" << endl;
ifstream infile;
infile.open("Example.txt", ios::in);
char data[20];
while (infile >> data) {
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << endl;
}
}
}
}
}
Here is the output:
The ╠ character is a box drawing character. In code page 437 it is represented by hex value 0xCC.
In this case it is a magic hex value that means it is uninitialised stack memory.
The data array is 20 characters long, but it degrades into a pointer and the operator<< outputs characters until it gets a null character. So in this case lots of uninitialized memory ╠ characters until a \0 character is found in memory.
It seems that the uninitialized data variable was written to the file on a previous run and now it is read back as-is. If the read was unsuccessful it would probably have placed a \0 in the first position of the data char array and there would have been no output in that case.
I ran the program with an empty input file and added a single student. This was stored in the text file (viewed with Visual Studio's text editor):
REGNUM123 Pete ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 00 00 PROC432
In this case Ì, or latin capital letter i with grave character is the 0xCC hex value in Unicode and multiple other encodings. When adding the student the number of characters written does not necessarily equal the number of characters in the data array (15 in that case). They are written until a \0 is found.
Most probably you have multiple buffer overruns:
char password[25];
cout << "Enter the admin password: ";
cin >> password;
If someone inputs more than 24 bytes (characters) as a password, you will have buffer overrun of password. You should do it this way:
std::string password;
cout << "Enter the admin password: ";
cin >> password;
The same thing is valid for output, you're potentially buffer overrunning char data[20];. Furthermore, you can't use infile >> data like that for reading from file. You have to use infile.getline():
int col_count = 4;
while (true) {
infile.getline(data, 20); // 20 is the size of the buffer.
if(infile.good()) {
cout << data;
if(--col_count == 0) {
col_count = 4;
cout << '\n';
}
else cout << '\t';
}
else break;
}

Unable to successfully compare strings

The idea is to take a file and print out the amount of words in the file. Then prompt the user to enter a word, the program will then count how many times that word is iterated. However I am having trouble with being able to pick out the chosen word from the file, no matter what it still returns 0.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream infile;
int i = 0;
string word_counter;
string file_name;
bool opened = false;
while (opened == false){
cout << "Enter the name of the file to read: ";
cin >> file_name;
infile.open(file_name, fstream::in);
opened = true;
if (!infile.is_open()) {
cout << "ERROR: CANNOT OPEN INPUT FILE" << endl;
cout << endl;
opened = false;
}
}
while (!infile.eof()){
infile >> word_counter;
cout << word_counter << endl;
i++;
}
cout << "Read in " << i << " words\n";
bool done = false;
while (!done){
string word;
string quit;
int x = 0;
cout << "Enter a word to count how many times it occurs: ";
cin >> word;
while (!infile.eof()){
infile << word_counter;
if (word_counter == word){
x++;
}
}
cout << "The word \"" << word << "\" occurs " << x << " times" << endl;
cout << "Press any key to continue, or press Q to quit: ";
cin >> quit;
if (quit == "q" || quit == "Q"){
done = true;
}
}
infile.close();
return 0;
}
You forgot to rewind the file.
Add the following lines
infile.clear(); // Clear the EOF flag
infile.seekg(0); // rewind
right after
cin >> word;
Also, you are using << instead of >> in the line
infile << word_counter;
Since you are not reading anything from the file, the enclosing while block stays in an infinite loop. Change that line to:
infile >> word_counter;

Unable to delete a record from a c binary program I created

thanks for your anticipated help. I have been looking at this code for hours and days but I just cant seem to find out why my delRecFunc() isn't deleting just one record at a time. It appears it is deleting the whole file.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
using namespace std;
const int NAME_SIZE = 40, ADDR_SIZE = 50, PHONE_SIZE = 14;
char y, Y;
struct Info
{
char name[NAME_SIZE];
int age;
char address1[ADDR_SIZE];
char phone[PHONE_SIZE];
}people;
void popFunc();
void dispFunc();
void appFunc();
void delRecFunc();
void searchFunc();
void modRecFunc();
int getNumRec();
int validateRecord (int);
void wipeFunc();
int main()
{
Info person;
char choice, option;
cout << " The file we are working with is named stuff.dat,\n"
<< "I will let you know if it unavailable " << endl;
cout << " "<< endl;
do
{
cout << " \n \n Simple People Records... \n \n \n "
<< " Please choose from the following options: \n \n \n"
<< " 1. POPULATE THE BINARY FILE \n"
<< " 2. DISPLAY THE CONTENTS OF THE FILE\n"
<< " 3. APPEND A RECORD TO THE FILE\n"
<< " 4. DELETE A RECORD FROM THE FILE\n"
<< " 5. SEARCH FOR A CERTAIN RECORD\n"
<< " 6. MODIFY A CERTAIN RECORD. \n"
<< " 7. WIPE OUT THE ENTIRE CONTENTS OF THE FILE. \n" <<endl;
cin >> option;
switch(option)
{
case '1': popFunc();
system("pause");
break;
case '2': dispFunc();
break;
case '3': appFunc();
break;
case '4': delRecFunc();
break;
case '5':searchFunc();
break;
case '6':modRecFunc();
break;
case '7':wipeFunc();
break;
}
}
while(choice!= 1000);
system("pause");
return(0);
}
void popFunc()
{ fstream file("stuff.dat", ios::out | ios::binary);
if (file.fail())
{
cout << "the file does not exist so we are creating it now... ";
system("pause");
file.open("stuff.dat", ios::out);
}
cout << "enter the following data about a person: "<<endl;
cout << "Name: " <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted): " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1: ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone: in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
file.write(reinterpret_cast<char *>(&people), sizeof(people));
file.close();
}
void dispFunc()
{
ifstream file;
file.open("stuff.dat", ios::binary);
if (file.fail())
{
cout << "the file does not exist so we are creating it now... ";
system("pause");
file.open("stuff.dat", ios::out);
}
while(file.read(reinterpret_cast<char *> (&people), sizeof(people)))
{
cout << "Name: "<< people.name <<endl;
cout << "Age: "<< people.age <<endl;
cout << "Address: " <<people.address1 <<endl;
cout << "Phone #: " <<people.phone << " \n\n"<<endl;
}
file.close();
}
void appFunc()
{ ofstream file;
file.open("stuff.dat", ios::binary | ios::app);
if (file.fail())
{
cout << "the file does not exist so we are creating it now... ";
system("pause");
file.open("stuff.dat", ios::out);
}
cout << "Name: " <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted): " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1: ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone: Phone: in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
file.write(reinterpret_cast<char *>(&people), sizeof(people));
file.close();
}
void searchFunc()
{
int count =1;
int answer;
long recNum;
int recCount = getNumRec();
fstream search;
search.open("stuff.dat", ios::in | ios:: binary);
cout << " Please enter 1 - " <<recCount ;
cout << " and I will display the data /n"<<endl;
cin >>recNum;
while(recNum<1 || recNum > recCount)
{
cout<<"Please enter a number between 1 and "<<recCount<<": ";
cin>>recNum;
}
answer = validateRecord(recNum);
}
void modRecFunc()
{
int count=1;
int answer;//to hold choice from the user
long recNum;//to hold a record number
int recCount = getNumRec();//variable to hold how many record the file has
fstream search;
//open file
search.open("stuff.dat",ios::in|ios::out|ios::binary);
cout<<"Which record do you wish to edit? ";
cin>>recNum;//variable to store the record the user wish to delete
//validation so the user is not allow to enter more numbers than the actual
//size of the file
while(recNum<1||recNum>recCount)
{
cout<<"Please enter a number between 1 and "<<recCount<<": ";
cin>>recNum;
}
//move pointer to desire position
cout<<endl;
answer= validateRecord(recNum);//make sure the record is the right one
cout<<endl;
if(answer==1)
{
//get the new data
cout << "Name: " <<endl;
cin >> ws;
cin.getline(people.name,NAME_SIZE);
cout << "Age (integers only or the program will be corrupted): " <<endl;
cin >> people.age;
cin.ignore(); //skip over the remaining newline.
cout<< "Address line 1: ";
cin >> ws;
cin.getline(people.address1,ADDR_SIZE);
cout << "Phone: Phone: in the following format ie: 201.123.1234 (no hyphens)";
cin >> ws;
cin.getline(people.phone,PHONE_SIZE);
search.seekp((recNum-1)*sizeof(people), ios::beg);
search.write(reinterpret_cast<char *>(&people), sizeof(people));
}
cout<<endl;
search.close();
}
void wipeFunc()
{ char option;
ofstream file;
cout << "This option will delete all the contents of the file "<<endl;
cout << " Are you sure you want to delete the file? Y or N " <<endl;
cin >> option;
if (option == 'y' || option == 'Y')
{
cout << " Warning, if you hit Y, you will lose everything " <<endl;
cout << " Y to confirm, N to return to main menu" <<endl;
cin >> option;
if(option == 'y' || option == 'Y')
{
file.open("stuff.dat", ios::out | ios::binary);
file.close();
}
}
}
int validateRecord (int recNum)
{
int answer;// variable to hold the answer from the user
fstream validate;
//open file
validate.open("stuff.dat",ios::in|ios::out|ios::binary);
validate.seekg((recNum-1)*sizeof(people));
//read record from file
validate.read(reinterpret_cast<char*>(&people),sizeof(people));
cout<<endl;
cout << "the name is "<< people.name <<endl;
cout << "the age is "<< people.age <<endl;
cout << "the address is" <<people.address1 <<endl;
cout << "the phone is Phone: " <<people.phone <<endl;
cout<<"Is this the file you want?\n"
"1. yes\n"
"2. no\n"
"Choice: ";
cin>>answer;
// validate answer to 1 or 2
while(answer<1||answer>2)
{
cout<<"enter only 1 or 2: ";
cin>>answer;
}
cout<<endl;
validate.close();
return answer;
}
int getNumRec()
{
int count =0;
fstream file;
file.open("stuff.dat", ios::in|ios::binary);
if (file.fail())
{
cout << "Error opening file. Program aborting.\n";
}
file.read(reinterpret_cast<char *>(&people),sizeof(people));
while (!file.eof())
{
count++;
file.read(reinterpret_cast<char *>(&people),
sizeof(people));
}
file.close();//close the file
return count;//return count the erase function
}
void delRecFunc()
{
int count=1;
int answer; //to hold choice from the user
double recNum;//to hold the record number the user wishes to delete
int recCount = getNumRec();//variable to hold how many record the file has
fstream erase;
erase.open("stuff.dat", ios::in|ios::out|ios::binary);
Info Temp; //*****NEW TEMP STRUCT VAR*****//
cout << "Please enter the phone number of the person you want to delete in this
format 201.123.1111)";
cin >> recNum;
//move pointer to desire position
erase.seekg((recNum-1)*sizeof(people));
//read record from file
erase.read(reinterpret_cast<char*>(&people),sizeof(people)); //read record from file
//get answer from the validateRecord function
answer = validateRecord (recNum);
if(answer == 1)
{
ofstream copy;
copy.open("stuff2.dat", ios::out | ios::binary);
erase.seekg(0*sizeof(people)); // Move pointer to beginning of the file
erase.read(reinterpret_cast<char*>(&people),sizeof(people));
// BEGIN NEW CODE //
// Keep looping till there are no more records in the customer.dat file
while (!erase.eof())
{
// If the id that the user wants deleted doesnt match the current
// records id, copy it to the temp directory
if(people.phone != Temp.phone)
{
// Write the record to copy.dat
copy.write(reinterpret_cast<char*>(&people),sizeof(Info));
}
// Read the next line from customer.dat
erase.read(reinterpret_cast<char*>(&people),sizeof(Info));
}
// Close both files
erase.close();
copy.close();
}
// Delete the Old customer.dat file
remove("stuff.dat");
// Rename the temporary holder to "customer.dat"
rename("stuff2.dat","stuff.dat");
}
You're taking an improperly formatted double (inputted from the cin >> recNum), seeking that far (*sizeof(people) into the file, and going from there. Seems like you need to start there.
Looks like you are entering the phone number in recNum (in the format 201.123.1111) and doing a seekg, which will give incorrect results