I'm trying to use a while loop to populate a set of arrays with data entered by a user. I am then passing the arrays to a function to be displayed when prompted by the user. The arrays have an unspecified size because I want the user to be able to enter as many items as they want.
From what I can tell, the program loops correctly, but does not store the data in the specified array on multiple passes. The data is overwritten by the next entry from the user (ie, when I tell the program to display an array, it will only display the last value it was assigned). I'm not sure if the problem is with my while loop or with the display function I used.
Any hints or help would be appreciated.
Here is my code:
Note: I removed some of the data entry fields and their variables to make the code a bit shorter and easier to read.
First of all, unfortunately in c++ (and c) you cannot define a variable sized array like that. When you write for example:
char mychar[] = {' '};
the compiler counts how many items are inside your braces and uses that for the size of the array. This will be the size of the array from now till eternity. So you can't use an array like this and keep adding elements to it. One solution that you can use is to just set the size of the array to a large value and hope that your users won't need more entries than that, or you can outright prevent them from adding more entries beyond the array size limit. So for example in your program, do something like this: int inventNum[1000];. This is not a great solution because if you try and access members beyond 1000, you will get a segmentation fault and your program will die.
I declared my arrays like you suggested (int inventNum[10]; ) and did a test run. Now it seems my program will recognize that there are supposed to be 10 items in the array, but it doesn't display them.
For example, I run the program, telling it to add a new book and then to add another new book. However, after I exit the addBook loop and try to display the list of authors in the authorOf array, I only get the last author entered followed by several lines of blank space (which I think is supposed to be the rest of the array, but since they have no data in there, a blank is displayed).
The only thing I can think of is that there is something wrong with my counter, but I've looked online and in my textbook and I can't seem to find the problem.
Yeah inside the loop for adding books you have int i = 0, every time this loop executes it will reset it to 0, so every book you add is only overwriting the first entry. Also you should look up std::vector as a replacement for your arrays, i think they would work better. http://www.cplusplus.com/reference/stl/vector/