Access to elements of an array of structures in C ++

Working with C ++ Primer Plus and trying to map data to a dynamically distributed array of structures. One element is a char array. How to write these structure elements? Posting the 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!

+3
source share
4 answers

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

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

also change access to

ptr[i].name
+2
source
cin >> ptr[i].name;

ptr - , contributions*. contributions, i- ptr[i]. name ptr[i].name. , cin >> char[] ( ), char[] C-ish, cin - ++. name std::string.

, , / . , contribution ; .

+3

Also, using the std :: vector contributions of w2, make the code a lot easier. as is, you have a memory leak. If it is straight from C ++ Primer Plus, I would seriously suggest moving on to a tutorial that will teach you modern, correct C ++, for example Accelerated C ++ by Koenig and Mu.

0
source

cin >> ptr[i].name;(the correct form) will stop at the first space character (and the risk of buffer overflows if such a character does not appear before 20 spaces in the array are exhausted). Use instead cin.getline(ptr[i].name, 20).

0
source

Source: https://habr.com/ru/post/1712569/


All Articles