tags:

views:

46

answers:

3
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main (){
 int a,b;
 b = 0;
cout<<" this is a family profiling program to test my knowledge of structural arrays. ";
 cin>> a;
 struct p {
char name[20];
int age;
char hobby[40];
char favcolor[15];
};
p family[2];
**cin.getline(family.name[0]);**
cout<<"enter the name of family member"<<b+1;

I am trying to use this code to create a family profiling program, i know how to add value to an array or structural array during compiler time but not to use cin or cin.getline to add a value to to a specific value in a specific structure of an array. please respond with a simple answer; Im still new to programming.(my attempt is bolded

A: 

If you insist on using an array, the easiest way to do this (add elements to a fixed-size array) would be to copy everything to a NEW array, including the new item.

A much better way would be to use a dynamic structure, such as a linked list. The standard template library and the boost library have many ways to help you here, but you could also easily implement a simple linked list on your own (or find code for it).

As Mike Chess said, this is probably best asked on http://www.stackoverflow.com

(also, to get your code formatted nicely, edit your post, select the code section, and click the button with the ones and zeros icon just above the text area)

FrustratedWithFormsDesigner
A: 

Firstly, you'll find it much easier to write reliable code if you use std::string instead of character arrays. You were nearly on the right track though: instead of family.name[0] try family[0].name, then getline will work with std::string as below...

struct p
{
    std::string name;
    // other stuff...
};

if (getline(std::cin, family[0].name))
{
    // it worked!
    ...
}
Tony
A: 

The "high performance" and old school option is to use realloc like this.

p * family = malloc(sizeof(p)*2);

family = realloc(family, sizeof(p)*13);

Of course this doesn't invoke constructors, and is not really acceptable in C++ generally. So your best option is.

#include <list>

using namespace std;

...

list<p> family;

p blah;

family.push_back(blah);

That's a linked list so it's perfect for datasets of unknown length. Same code can be used for an STL vector, which if you predict the size of your input in advance well enough will give you a performance boost.

Novikov