-
Phone Book in C++
Im having trouble loading data to arrays in C++. I have to make a phone book where the first thing you do is click on a button called load and then load two files, one called names.txt the other called phonenumbers.txt, to two parallel arrays. here is what i got so far. I'm so lost, any help will do.
[code]
int index = 0;
ifstream name_database;
name_database.open("F:\\pb\\names.txt");
name_database >> names[];
ifstream phone_database;
phone_database.open("F:\\pb\\phonenumbers.txt");
phone_database >> phone_number[];
for (index=0;index<5;index++)
names[index] = index+1;
[code]
ive declared my arrays globally, im programming in windows using borland
-
Code:
int counter = 0; // counter for array locations
char names[10][80]; // array of 10 strings each of 79 chars, just for example, yours are global
string line; // getting each individual line from the file
ifstream txtfile ("names.txt"); // input stream
if (txtfile.is_open()) // checking if the file is open
{
while (! txtfile.eof() ) // while the stream isn't at the end of the file
{
getline (txtfile, line); // getting each line individually
names[counter] = line; // place the line retrieved from the file into the array
counter++; // advance the counter
}
txtfile.close(); // close the file
}
now this is a rough unchecked way of putting input from a stream into an array. now just make this a function, and pass in a string or pointer with the names of the files and you can easily do both files without repeating code.
-
Thanks for the help, i couldnt get your code to work, i got a Lvalue required error in borland, so i modified it a bit.
Code:
int counter_ph = 0; // counter for array locations
int counter = 0; // counter for array locations
ifstream name_database; // input stream
name_database.open("names.txt");
while (! name_database.eof()) // while the stream isn't at the end of the file
{
name_database >> names[counter];
counter++; // advance the counter
}
ifstream phone_database; // input stream
phone_database.open("phonenumbers.txt");
while (! phone_database.eof() ) // while the stream isn't at the end of the file
{
phone_database >> phone_number[counter_ph];
counter_ph++; // advance the counter
}
what do you think csl
-
oops, sorry about that, in my code i needed a string array instead of a char array. regarding your code, why not just make the data retrieval process a function and then call it whenever necessary, passing in a filename and a pointer to the array you want the data stored in. also you have two counters, one of which is un necessary.