C++ FSTREAM & classes - c++

Okay so when I started using classes to make functions, it gives me an error file is invalid, normally doesn't if I don't use classes. If you run it, enter in some info, and then run it again, normally it should read in the data correctly, it still reads it in, but it says there's an error. I don't really know what I'm doing wrong, any tips? Thanks!
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;
const int TEMP_SIZE = 10;
const int NAME_SIZE = 100;
const int BREED_SIZE = 100;
const int DESC_SIZE = 250;
const int REASON_SIZE = 250;
const int ID_SIZE = 50;
//creating the struct
struct animal
{
char name[NAME_SIZE];
char ID[ID_SIZE];
char breed[BREED_SIZE];
float age;
float weight;
char desc[DESC_SIZE];
char reason[REASON_SIZE];
int day;
int month;
int year;
float length;
};
struct adopted
{
char hostName[100];
char hostAddress[100];
int numPets;
};
class petAdoption
{
public:
petAdoption();
//~petAdoption();
void enroll(animal newAnimal[]);
void read(animal newAnimal[]);
private:
int count;
int numPets;
int * pets;
};
petAdoption::petAdoption()
{
count = 0;
pets = NULL;
numPets = 0;
}
void petAdoption::enroll(animal newAnimal[])
{
cout << "Please enter your pet's name: ";
cin.get(newAnimal[count].name, NAME_SIZE, '\n');
cin.ignore(100, '\n');
cout << "Please enter a unique ID for your pet (combinations of numbers EG: 432FD3): ";
cin.get(newAnimal[count].ID, ID_SIZE, '\n');
cin.ignore(100, '\n');
cout << "What type of breed is your pet?: ";
cin.get(newAnimal[count].breed, BREED_SIZE, '\n');
cin.ignore(100, '\n');
cout << "How old is your pet?: ";
cin >> newAnimal[count].age;
cin.ignore(100, '\n');
cout << "How much does your pet weigh? (in LBS): ";
cin >> newAnimal[count].weight;
cin.ignore(100, '\n');
cout << "Please describe your pet's personality!: ";
cin.get(newAnimal[count].desc, DESC_SIZE, '\n');
cin.ignore(100, '\n');
cout << "Please explain why the pet is being put up for adoption: ";
cin.get(newAnimal[count].reason, REASON_SIZE, '\n');
cin.ignore(100, '\n');
cout << "Please enter your pet's day of birth (1-31): ";
cin >> newAnimal[count].day;
cin.ignore(100, '\n');
cout << "Please enter your pet's month of birth (1-12): ";
cin >> newAnimal[count].month;
cin.ignore(100, '\n');
cout << "Please enter your pet's year of birth (1900-2012) : ";
cin >> newAnimal[count].year;
cin.ignore(100, '\n');
cout << "Please enter the length of time your pet has spent in a shelter (in months): ";
cin >> newAnimal[count].length;
cin.ignore(100, '\n');
/*** WRITES the pet ID into the list of pets***/
ofstream write;
write.open("pets.txt", ios::app);
write << newAnimal[count].name << '\n';
write.close();
/*** WRITES EACH PET INFO ****/
//this opens the file / creates a file if it's not made yet
//and it writes the pet's information
write.open(newAnimal[count].name, ios::app);
write << newAnimal[count].name << '\n'
<< newAnimal[count].ID << '\n'
<< newAnimal[count].breed << '\n'
<< newAnimal[count].age << '\n'
<< newAnimal[count].weight << '\n'
<< newAnimal[count].desc << '\n'
<< newAnimal[count].reason << '\n'
<< newAnimal[count].day << '\n'
<< newAnimal[count].month << '\n'
<< newAnimal[count].year << '\n'
<< newAnimal[count].length << '\n';
//this closes the file
write.close();
}
void petAdoption::read(animal newAnimal[])
{
ifstream read;
//open the file apps.txt
read.open("pets.txt");
//if apps.txt doesn't exist, then print out this error
if(!read)
{
cout << "pets.txt doesn't exist! This is your first time!" <<endl;
}
//else if it does exist, read in the names and store them back
//into the struct member name(s)
else
{
//while the document isn't empty
//read in each line
while(!read.eof())
{
read.getline(newAnimal[count].name, NAME_SIZE, '\n');
++count;
}
count = count-1;
}
//close the file
read.close();
for (int i = 0; i < count; ++i)
{
//open the file of the name of the app
read.open(newAnimal[count].name);
//if the file doesn't exist
//then we probably deleted it
//without removing it from the apps.txt
//but it prints out an error
if( !read)
{
cout << "invalid file!" <<endl;
}
//however if the file does exist,
//read in each line and store them back
//into the struct members
while(!read.eof())
{
read.getline(newAnimal[count].name, NAME_SIZE, '\n');
read.ignore(100, '\n');
read.getline(newAnimal[count].ID, ID_SIZE, '\n');
read.ignore(100, '\n');
read.getline(newAnimal[count].breed, BREED_SIZE, '\n');
read.ignore(100, '\n');
read >> newAnimal[count].age;
read.ignore(100, '\n');
read >> newAnimal[count].weight;
read.ignore(100, '\n');
read.getline(newAnimal[count].desc, DESC_SIZE, '\n');
read.ignore(100, '\n');
read.getline(newAnimal[count].reason, REASON_SIZE, '\n');
read.ignore(100, '\n');
read >> newAnimal[count].day;
read >> newAnimal[count].month;
read >> newAnimal[count].year;
read >> newAnimal[count].length;
read.ignore(100, '\n');
}
//close the file
read.close();
}
}
int main()
{
animal newAnimal[10];
petAdoption adopt;
adopt.read(newAnimal);
adopt.enroll(newAnimal);
}

I think I know what's going on. when you say read.open("pets.txt"); it should say read.open("pets.txt"),ios::app because then it so snot delete the data it already stores. Also go in to your file explorer and search pets.txt and read it to see what's going on. I hope I helped you.

Related

CPP infinit while-loop error when reading in struct data?

I would like to use an infinite loop to read in Person struct (name, age, salary). I would like to break the loop when the user enters name as 'x'.
#include <iostream>
#include <vector>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main(int argc, const char * argv[]) {
Person p1;
vector <Person> p1_vec;
while (true) {
cout << "Enter Full name or simply 'x' to exit: ";
cin.get(p1.name, 50);
bool next_entry = strcmp(p1.name,"x");
if (!next_entry) {
break;
}
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
p1_vec.push_back(p1);
}
}
You need to ignore the new line character that you get after reading a salary input:
cin >> p1.salary;
doing:
cin >> p1.salary;
cin.ignore(1, '\n');
will make the code to stop here:
cin.get(p1.name, 50);
and wait for another user input!
cin state needs to be cleared after reading, try something like:
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
For example (depending on the amount of error tolerance you want)
while (true)
{
cout << "Enter Full name or simply 'x' to exit: ";
cin.get(p1.name, 50);
cin.clear();
auto equal = strcmp(p1.name, "x")==0;
if (equal)
{
break;
}
cout << "Enter age: ";
cin >> p1.age;
cin.clear();
cout << "Enter salary: ";
cin >> p1.salary;
p1_vec.push_back(p1);
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
cin.get(p1.name, 50) does not consume the \n, that remains in the input buffer after having entered a salary; so it skips the input and leaves the values blank.
Write cin >> p1.name and it should work properly.
After getting data from input buffer, you should clear it.
int main(int argc, const char * argv[]) {
Person p1;
vector <Person> p1_vec;
while (true) {
cout << "Enter Full name or simply 'x' to exit: ";
cin.get(p1.name, 50);
bool next_entry = strcmp(p1.name,"x");
if (!next_entry) {
break;
}
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
p1_vec.push_back(p1);
cin.clear();
cin.ignore();
}
}

While loop not breaking, using cin.ignore and cin.clear() to verify input

I'm trying to use a loop to verify that the input grade is an integer, but when I intentionally input a char, the program does nothing. It only starts a newline upon pressing enter.
void fillvector(vector<student>& parameter)
{
string newname;
int newgrade;
int number;
cout << "How many students are in your class: ";
cin >> number;
for (int i = 0; i < number; i++)
{
cout << endl << "Enter student name: ";
while (1)
{
cin >> newname;
cout << "Enter student grade: ";
cin >> newgrade;
if (cin.fail())
{
cout << endl << "Grade must be an integer value, try again.";
cin.clear();
cin.ignore(INT_MAX);
i--;
break;
}
else
{
student student(newname, newgrade);
parameter.push_back(student);
break;
}
}
}
cout << endl;
}
cin.ignore(INT_MAX);
This will make cin ignore any further characters you enter up to MAX_INT..
What you wanted is to ignore up-to the next newline:
cin.ignore(INT_MAX, '\n');
Besides, there is no point in making a while(1) loop that will break in all paths in the first iteration. You can remove that inner loop.

file i/o problems with task tracker

I have been trying to make a task tracker console application that is able to perform three different functions --> add a task, show the task list, and search task list by classname. My code for adding a task works fine, but im trying to work out how to display the task list properly, but it keeps outputting only part of the tasks.
for example if you add the task CS162;Lab Due;04/20/2014 and the task
MTH251;Quiz;04/22/2014. If you close the file and look at it, they were written to tasks.txt fine, but when i go to read them back, the output looks like:
Due04/20/2014
MTH251Quiz
which is only a fraction of the desired output.
I also need to search by name but I think I can figure that out easily after I figure out the other issue
my textfile looks like this:
CS162;Lab Due;04/20/2014
MTH251;Quiz;04/22/2014
and my code looks like this:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
ofstream outFile;
ifstream inFile;
const int MAXCHAR = 101;
const int MAXLINE = 256;
struct task
{
char course[MAXCHAR];
char desc[MAXCHAR];
char date[MAXCHAR];
};
int main()
{
task track;
bool quit = false;
while (quit == false)
{
char choice;
cout << "Welcome to my Task List: \n";
cout << "<a> to add task\n";
cout << "<s> to show the task list\n";
cout << "<f> to find a task by course name\n";
cout << "<q> to quit\n";
cin >> choice;
cin.ignore(100, '\n');
if (choice == 'a' || choice == 'A')
{
outFile.open("tasks.txt", fstream::app);
cout << "Enter Course Name (less than 101 characters): ";
cin.get(track.course, MAXCHAR, '\n');
cin.clear();
cin.ignore(100, '\n');
cout << "Enter Task Description (less than 101 characters): ";
cin.get(track.desc, MAXCHAR, '\n');
cin.clear();
cin.ignore(100, '\n');
cout << "Enter due date (mm/dd/yyyy): ";
cin.get(track.date, MAXCHAR, '\n');
cin.clear();
cin.ignore(100, '\n');
char confirm;
cout << "\nAre you sure you want to add " << track.course << ";" << track.desc << ";" << track.date << "? (y/n)";
cin >> confirm;
if (confirm == 'y' || confirm == 'Y')
{
cin.clear();
cin.ignore(100, '\n');
outFile << track.course << ";" << track.desc << ";" << track.date << "\n";
cout << "Task has been added\n";
}
else if (confirm == 'n' || confirm == 'N')
{
cin.clear();
cin.ignore(100, '\n');
}
outFile.close();
}
else if (choice == 's' || choice == 'S')
{
inFile.open("tasks.txt");
char str[MAXCHAR];
while (inFile >> str)
{
inFile.getline(track.course, MAXLINE, ';');
inFile.getline(track.desc, MAXLINE, ';');
inFile.getline(track.date, MAXLINE, ';');
cout << track.course << track.desc << track.date;
}
inFile.close();
cin.clear();
cin.ignore(100, '\n');
}
else if (choice == 'f' || choice == 'F')
{
char course[MAXCHAR];
cout << "Enter Course Name: ";
cin >> course;
inFile.open("tasks.txt");
while (!inFile)
{
}
inFile.close();
}
else if (choice == 'q' || choice == 'Q')
{
cin.clear();
cin.ignore(100, '\n');
quit = true;
}
}
}
edit:
I now have the "show task list" working properly, but can somebody explain to me why using something like this doesnt work for the "search course"??
else if (choice == 'f' || choice == 'F')
{
char course[MAXCHAR];
cout << "Enter Course Name: ";
cin >> course;
inFile.open("tasks.txt");
while (inFile)
{
inFile.getline(track.course, MAXLINE, ';');
inFile.ignore(100, '\n');
while (strcmp(course, track.course) != 0)
{
cout << track.course;
}
}
}
while (inFile >> str) {
inFile.getline(track.course, MAXLINE, ';');
inFile.getline(track.desc, MAXLINE, ';');
inFile.getline(track.date, MAXLINE, ';');
std::cout << track.course << track.desc << track.date;
}
The first line will read all chars into str until it hits the first whitespace, so if your input is
CS162;Lab Due;04/20/2014
MTH251;Quiz;04/22/2014
it will read up to and including Lab into str.
The next three lines will read until they hit ;, so your track struct will look as follows
course = "Due"
desc = "04/20/2014\nMTH251" // note the newline
date = "Quiz"
Changing the while loop and changing the last extractor should fix this:
while (inFile) {
inFile.getline(track.course, MAXLINE, ';');
inFile.getline(track.desc, MAXLINE, ';');
inFile.getline(track.date, MAXLINE, '\n');
if (inFile)
std::cout << track.course << track.desc << track.date;
}
although it's worth mentioning that there are a number of things you can do here to simplify the code, including using std::string instead of char arrays, like this for instance.

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

Fstreams C++ has extra spaces on writing

I figured some stuff out, but I suck at fstreams, and this is just killing me, for BREED + DESC, they have a space between them and name, but when I remove them completely then I get no spaces and it works again. Could someone tell me what I'm doing wrong?
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;
const int NAME_SIZE = 100;
const int BREED_SIZE = 100;
const int DESC_SIZE = 250;
const int REASON_SIZE = 250;
//creating the struct
struct animal
{
//members
char name[NAME_SIZE];
char breed[BREED_SIZE];
char desc[DESC_SIZE];
char reason[REASON_SIZE];
float age;
float weight;
int day;
int month;
int year;
float length;
};
class petAdoption
{
public:
petAdoption();
void enroll(animal newAnimal[], int & count);
void read(animal newAnimal[], int & count);
//void display(animal & newAnimal);
//void adopt(animal & newAnimal);
private:
};
petAdoption::petAdoption()
{
}
int main()
{
int count = 0;
animal * newAnimal = new animal[count];
petAdoption adopt;
adopt.read(newAnimal, count);
adopt.enroll(newAnimal, count);
delete[] newAnimal;
}
void petAdoption::read(animal newAnimal[], int & count)
{
int pets = 0;
ifstream read;
read.open("pets.txt");
if(!read)
{
cout << "Checking... File doesn't exist!" <<endl;
}
else
{
while(!read.eof())
{
read.getline(newAnimal[pets].name, NAME_SIZE, '\n');
read.ignore(100, '\n');
++pets;
}
count = pets + 1;
}
read.close();
for (int i = 0; i < pets; ++i){
read.open(newAnimal[i].name);
if( !read)
{
cout << "Checking... File doesn't exist!" <<endl;
}
else{
while(!read.eof())
{
read.getline(newAnimal[i].name, NAME_SIZE, '\n');
read.getline(newAnimal[i].breed, BREED_SIZE, '\n');
read.getline(newAnimal[i].desc, DESC_SIZE, '\n');
read.getline(newAnimal[i].reason, REASON_SIZE, '\n');
read.ignore(100, '\n');
read >> newAnimal[i].age;
read >> newAnimal[i].weight;
read >> newAnimal[i].day;
read >> newAnimal[i].month;
read >> newAnimal[i].year;
read >> newAnimal[i].length;
read.ignore(100, '\n');
}
}
read.close();
}
}
/*
ENROLL FUNCTION
*/
void petAdoption::enroll(animal newAnimal[], int & count)
{
//making a write variable
ofstream write;
//stores the name into the struct member
cout << "Please enter a name: ";
cin.get(newAnimal[count].name, NAME_SIZE, '\n');
cin.ignore(100, '\n');
cout << "Please enter a breed: ";
cin.get(newAnimal[count].breed, BREED_SIZE, '\n');
cin.ignore(100, '\n');
cout << "Please enter a desc: ";
cin.get(newAnimal[count].desc, DESC_SIZE, '\n');
cin.ignore(100, '\n');
cout << "Please enter a reason (EG: eats people): ";
cin.get(newAnimal[count].reason, REASON_SIZE, '\n');
cin.ignore(100, '\n');
cout << "Please enter an age (EG: 5): ";
cin >> newAnimal[count].age;
cin.ignore(100, '\n');
cout << "Please enter a weight (in LBS): ";
cin >> newAnimal[count].weight;
cin.ignore(100, '\n');
cout << "Please enter a day (EG: 2): ";
cin >> newAnimal[count].day;
cout << "Please enter a month (EG: 11): ";
cin >> newAnimal[count].month;
cout << "Please enter a year (EG: 2002): ";
cin >> newAnimal[count].year;
cout << "How long has the pet been in a shelter? (in months): ";
cin >> newAnimal[count].length;
//error
if(!write)
{
cout << "Invalid File" << endl;
}
else{
write.open(newAnimal[count].name, ios::app);
write << newAnimal[count].name << '\n'
<< newAnimal[count].breed << '\n'
<< newAnimal[count].desc << '\n'
<< newAnimal[count].reason << '\n'
<< newAnimal[count].age << '\n'
<< newAnimal[count].weight << '\n'
<< newAnimal[count].day << '\n'
<< newAnimal[count].month << '\n'
<< newAnimal[count].year << '\n'
<< newAnimal[count].length << '\n';
write.close();
}
if(!write)
{
cout << "Invalid File";
}
else {
write.open("pets.txt", ios::app);
write << newAnimal[count].name << '\n';
write.close();
}
}
As people mention (in response to an earlier version of this question already) you shall not use eof() to control your loop . Furthermore you shall test that you successfully received your input after you [attempted] to read it.
The problem with extra newlines at the end if a line is due to your use of get() rather than getline(): the former retains the stop character while the latter does not. You should als consider using std::string together with std::getline(): it reads arbitrary length strings.