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!
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
cin >> ptr[i].name;
ptr - , contributions*. contributions, i- ptr[i]. name ptr[i].name. , cin >> char[] ( ), char[] C-ish, cin - ++. name std::string.
ptr
contributions*
contributions
ptr[i]
name
cin >> char[]
char[]
cin
, , / . , contribution ; .
contribution
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.
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).
cin.getline(ptr[i].name, 20)
Source: https://habr.com/ru/post/1712569/More articles:Ratings - at what coefficient should they be reduced when adding another developer? - project-planningУлучшение производительности и скорости Watin - performanceMoving R-Graphics Header - rFlash: как я могу временно отключить или заблокировать все события мыши для SWF файла, загружаемого извне - actionscriptFilter SELECT statements by row with most populated columns - sql-serverIs the POD class initialized with default allocation initialization? - c ++https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1712571/passing-multiple-parameters-to-a-controller&usg=ALkJrhhmJykYXM1T6hlGfiVbLM2IxNeqUgDo I need MSI for every OS? - windows-installeropen a new html page through php - htmlhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1712574/using-css-to-grab-all-available-vertical-space&usg=ALkJrhiyeYfIsFRMepSmE0scsMOBLr2eZQAll Articles