0

I need to read information from a text file into a struct array. Im writing a program to make a list of favorites that the user will input. When they close the program, the array will write to a file. The next time the program is ran, i need to read in the file and continue the array where i left off. I need to read in 3 parts to the struct. Here is what i have so far, with some play code that i was trying.

// assumptions: 100 favoriates at most
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

// data structure

struct favorite
{
	int id;
	string url;				
	string annotation;
	// to deal with file operations, better use 
	// char url[100]; 
	//then you need to use strcmp, strcpy functions etc.
};

const int MAX=100;

struct favorite fs[MAX];

void writearecord(struct favorite af, int index)
{

	fs[index].id=af.id;
	fs[index].annotation=af.annotation;
	fs[index].url=af.url;
	
}

void dptable(int upplimit)
{
	for(int i=0; i<upplimit; i++)
	{
		ifstream("favlist.txt");
		cout<<fs[i].id<<"  "<<fs[i].url<<"  "<<fs[i].annotation<<endl;
	}
}

int main()
{
	struct favorite onefavorite;
	

	//onefavorite.id=1;
	//onefavorite.url="www.google.com";
	//onefavorite.annotation="search engine";
	
	//writearecord(onefavorite, 0);
	dptable(3);
	ofstream outf("favlist.txt", ios::app);
	
	for (int i=0; i<3; i++)
	{
		onefavorite.id =i;
		cout << "Please enter URL: " ;
		cin >> onefavorite.url;
		cout << "Enter annotation: " ;
		cin >> onefavorite.annotation ;
		outf << onefavorite.id<<" " << onefavorite.url<<" " << onefavorite.annotation << endl;
		
		writearecord(onefavorite, i);
	}
	
	dptable(3);

	return 0;
}

and my text file
0 www.aol.com Mail
1 www.cnet.com Tech
2 www.yaoo.com SE

i need to read the "0" into .id, the www.aol.com into the .url, and "mail" into .annotation then read in the next line of data.
I just am just starting to get into programming so any help would be greatly appreciated.

2
Contributors
1
Reply
4
Views
8 Years
Discussion Span
Last Post by Ancient Dragon
0

1. USE CODE TAGS!

2. Move the open statement up outside the loop.

void dptable(int upplimit)
{
    ifstream("favlist.txt");
    for(int i=0; i<upplimit; i++)
   {
       cout<<fs[i].id<<" "<<fs[i].url<<" "<<fs[i].annotation<<endl;
   }
}

3. Delete that ofstream object that you put in main() -- it serves no purpose and may cause problems with the write function.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.