tags:

views:

189

answers:

4

Working through C++ Primer Plus and am trying to cin data to a dynamically allocated array of structures. One of the items is a char array. How do I write to these struct members? Posting code of my wrong attempt so you can see what I'm trying to do.

    #include <iostream>
using namespace std;

struct contributions
{
    char name[20];
    double dollars;
};

int donors;

int main()
{
    cout << "How many contributors will there be?\n";
    cin >> donors;
    contributions * ptr = new contributions[donors];
    for(int i = 0; i <= donors; i++)
    {
        cout << "Enter donor name #" << i+1 << ": \n";
        cin >> ptr->contributions[i].name;
        cout << "Enter donation amount: \n";
        cin >> ptr->contributions[i].dollars;
    }

Thanks in advance!

+1  A: 

Try using std::string instead of char[20] for name and the sample should work just fine.

struct contributions
{
    std::string name;
    double dollars;
};

also change the access to

ptr[i].name
JaredPar
22|error: invalid use of `struct contributions'|I changed the line to "string name;" and received that error.
scribbles
+2  A: 
cin >> ptr[i].name;

ptr is the name of the variable, it is of type contributions*. It is an array of contributions, so to access the ith member, use ptr[i]. Then access the name field of that member via ptr[i].name. Also, cin >> char[] may not work (I don't recall for sure), as char[] is more of a C-ish thing, whereas cin is C++. So you might need to change the type of name to std::string.

As an aside, convention is to name your structs/classes with a singular noun. Thus contribution would be a more correct name; every instance represents a single contribution.

Nick Lewis
I was just writing this when you posted it... +1. I'm confused as to how the OP's code even compiled.
rmeador
Well the OP never said what exactly went wrong with his code; my guess is that it actually wasn't compiling.
Nick Lewis
I apologize for the confusion. Yes, it wasn't compiling, stating that I was referencing the struct contributions wrong. Thanks for the correction on the naming convention, I didn't know that.
scribbles
A: 

Also, using a std::vector of contributions w2ill make the code much simpler. as it is, you have a memory leak. If this is direct from C++ Primer Plus I'd seriously suggest changing to a text book that will teach you modern, correct C++, such as Accelerated C++ by Koenig & Moo.

anon
A: 

cin >> ptr[i].name; (the correct form) would stop at the first whitespace character (and risk a buffer overflow if no such character comes before the 20 spaces in the array are exhausted). Use cin.getline(ptr[i].name, 20) instead.

Alex Martelli
What would the "20" in that line be if I changed it to a "char name[20]" in the struct to "string name"?
scribbles
Then you wouldn't need to provide that number (string will grow as needed).
Alex Martelli