Reputation: 58
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!
Upvotes: 3
Views: 6356
Reputation:
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.
Upvotes: 0
Reputation: 881675
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.
Upvotes: 0
Reputation: 4230
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.
Upvotes: 3
Reputation: 754745
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
Upvotes: 2