So I know how to delete a descriptor from an array, but I can't seem to edit the code to add a new line to the data. The line consists of a name, one space, and then a 3 digit number. I was wondering if anyone could help me edit my existing code to the the reverse.

#include <iostream>
#include <fstream>
using namespace std;
const int NAMEMAX=50;
struct record
{
char name[NAMEMAX];
int vote;
};
bool trytoread(ifstream *pf, record *pr)
{
*pf>>pr->name; //(*pr).name
*pf>>pr->vote;
if(!*pf)
return false;
return true;
}
int find(record data[],int count, char name[NAMEMAX])
{
for(int i=0;i<count;i++)
if(strcmp(name,data[i].name)==0)
return i;
return -1; //not a valid index
}
int main ()
{
record data[100];
int count=0;
char name[NAMEMAX];
ifstream input;
input.open("votes.txt");
if(!input)
{
cout<<"bad open"<<endl;
exit(1);
}
while(trytoread(&input,&data[count]))
count=count+1;
input.close();
cout<<"type a name: ";
cin>>name;
int index=find(data,count,name);
if(index==-1)
cout<<"invalid descriptor"<<endl;
else
{
data[index]=data[count-1];
count=count-1;
}
for(int i=0;i<count;i++)
cout<<data[i].name<<" "<<data[i].vote<<endl;
return 0;
}

>>So I know how to delete a descriptor from an array,
define descriptor

oh im sorry, it's just a line in the text file that is opened. The text file I'm opening contained 5 names with a 3 digit number behind it. One name and number per line. My code above asks for a name and then deletes it, if it is in the text file, and the prints the remaining names and numbers. I just can't seem to add a name and number.

You have to have the file opened for output if you want to add a line to the file. Then seek to the end of the file and write the new data.

This article has been dead for over six months. Start a new discussion instead.