Need help with adding to and searching through a list.

Hi guys!

The program I'm using revolves around the following structure:

struct people
int ID;
char name[30];
char address[50];

The first thing I do is read in 6 IDs / names / addresses from a text file. This part works fine using an array of structures.

The program then sorts these structures by ID and prints them. This part also works fine.

Here's where it goes south:

I then ask the user if they want to add a new entry. If they say yes then the following code runs:

void add(people z[], int counter)
cout << "Enter the ID: " << endl;
cin >> z[counter].ID;
cout << "Enter the name using the format (Last name,First name): " << endl;
cin >> z[counter].name;
cout << "Enter the address using format (Street, City, State Zip): " << endl;
cin >> z[counter].address;

Entering the ID works (i.e. 234982).
Entering the name works (i.e. Smith,Joe).
Entering the address does not work (i.e. 8492 Blue St., Detroit, MI 29839).

The address isn't working because there are spaces in it. If I add a space in the other fields it messes up as well, but those other fields don't need a space. Anyone know what's wrong? It stores what is before the first space as the address and everything after the first space is treated as the next command input.

edit: I forgot to ask about searching through the names as well. Currently I'm using the following code to search:

void search(people z[], int counter)
char searchTerm[30];
cout << "Enter the last name of the person (with a capital first letter): " << endl;
cin >> searchTerm;
cout << endl;
for(int i = 0; i < counter; i++)
if(strncmp(searchTerm, z[i].name, 3) == 0)
cout << z[i].ID << endl;
cout << z[i].name << endl;
cout << z[i].address << endl << endl;

This code asks you for a name to search for (i.e. Jillian). It then uses strncmp to compare what you searched for to all of the entries. If it matches at least 3 of the letters in a row, it returns the ID, name, and address of that person.

The problem is that matching 3 letters is not efficient and definitely won't always work. For example, what if the name is less than 3 letters, or what if two people have the same first 3 letters?

Thanks in advance!
1) Use getline instead of cin.

2) Separate first name and last name variables, so you can use full match(strcmp). If you want to store first and last name in same string, in searching, first explode string by comma(,) and use full match(strcmp)
Topic archived. No new replies allowed.