When I'm searching an integer in my dynamic array, the search function isn't working well as its always showing its positioned at 1. whether the data is actually there or not.
What i'm actually trying to do is using dynamic data structure, I'm adding the data. Deleting, searching and saving to txt file. and Loading it back. But the problem is search. I used switch cases and search is at Case 4.
#include<iostream>
#include<string>
#include<fstream> //to save file in text
using namespace std;
int main()
{
int *p1;
int size = 0;
int counter = 0;
p1 = new int[size];
int userchoice;
int i;
int position;
while (1)
{
cout << "Please enter your choice " << endl;
cout << endl;
cout << "To insert Press '1'" << endl;
cout << "To Delete press '2'" << endl;
cout << "To View press '3'" << endl;
cout << "To Search press '4'" << endl;
cout << "To Save Press '5'" << endl;
cout << "To Load Previously saved Data press '6'" << endl;
cout << "To Exit press '7'" << endl;
cout << endl;
cout << "Enter your choice: ";
cin >> userchoice;
switch (userchoice) // User's selection from the menu
{
case 1: //Insert Number
cout << "Enter a Number: ";
cin >> p1[size];
counter++;
size++; //Add's memory space
break;
case 2: //Delete Number
int udelete;
cout << "Enter a number to delete: ";
cin >> udelete; //User enters Number to be deleted
//Checking if the number is in an array.
for (position = 0; position<size; position++)
{
if (p1[position] == udelete)
break;
}
if (position>size)
{
cout << "The number is not in the memory: ";
cout << endl;
break;
}
for (i = position; i<size; i++) {
p1[i] = p1[i + 1];
}
size--;
cout << "Successfully Deleted!!! ";
cout << endl;
break;
case 3: // View
for (i = 0; i<size; i++)
{
cout << "Your data" << " " << i << " " << "-->" << p1[i] << endl;
}
break;
case 4:
{
int usearch;
cout << "Please enter the figure you would like to search ";
cout << "->";
cin >> usearch;
for (i = 0; i>size; i++)
{
if (p1[size] == usearch)
break;
}
if (usearch == size)
{
cout << "not found. ";
}
cout << "Position at: " << i + 1 << endl;
break;
}
case 5: // Save
{
ofstream save;
save.open("Dynamicdata.txt", ofstream::out | ofstream::app);
for (i = 0; i<size; i++)
{
save << p1[i] << endl;
}
save.close();
cout << "File Saved " << endl;
break;
}
case 6: //Read from File
{
string read;
ifstream file_("Dynamicdata.txt");
if (file_.is_open())
{
while (getline(file_, read))
{
cout << read << "\n";
}
file_.close();
}
else
cout << "File Not open" << endl;
cin.get();
break;
}
case 7:
{
return 0;
}
}
}
}
Your problem is that the size of your array is 0. Here you set size to 0 and then size for the size of p1
int size=0;
int counter=0;
p1 = new int[size];
You are going to need to make size bigger so that you can actually store elements in p1 or instead of using arrays and dynamic memory allocation use a std::vector and let it handle that for you.
The code has undefined behaviour because initailly the dynamically allocated array pointed to by pointer p1 has no elements
int size=0;
^^^^^^^^^^
//...
p1 = new int[size]; // size is equal to 0
So in the following code snippet an atttempt to write data to p1[size] results in undefined behaviour
case 1: //Insert Number
cout<<"Enter a Number: ";
cin>>p1[size]; // undefined behaviour
^^^^^^^^^^^^^
counter++;
size++; //Add's memory space
break;
You need to reallocate the array to reserve memory for the added new element.
Take into account that for example this loop
for (i = 0; i>size; i++)
^^^^^^^
{
if (p1[size] == usearch)
break;
}
will never iterate because variable i set to zero can not be greater than size that at least equal to zero.
And it would be logically more correct to write
if (p1[i] == usearch)
^^^^^
instead of
if (p1[size] == usearch)
^^^^^^^^
Consequently this if statement
if (usearch == size)
^^^^^^^
{
cout << "not found. ";
}
should be replaced with this for statement
if (i == size)
^^
{
cout << "not found. ";
}
Related
This question already has answers here:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
(11 answers)
Variable length arrays (VLA) in C and C++
(5 answers)
Closed 6 months ago.
What does " control reaches end of non-void function" means??
How to remove the warnings from out code ?
#include <bits/stdc++.h>
using namespace std;
int LinearSearch()
{
int ans=-1;
cout << "Enter the Size of the array: \n";
int n;
cin >> n;
cout << "Enter the array elements: \n";
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int key;
cout << "Enter the key: \n";
cin >> key;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
cout << "the " << key << " is found at index " << i << endl;
}
return ans;
}
}
int main()
{
while (1)
{
cout << "\t Main Menu\n";
cout << "1. For Linear Search\n";
cout << "2. For Binary Search\n";
cout << "3. For First and last Occurence\n";
int ch;
cout << "Enter the choice: \n";
cin >> ch;
switch (ch)
{
case 1:
cout<< LinearSearch();
break;
case 2:
break;
case 3:
break;
default:
cout << "Invalid Choice OOps!! ";
break;
}
}
return 0;
}
enter image description here
AS I am trying to run it it is giving me Warning Why??
Error is: warning: control reaches end of non-void function [-Wreturn-type]
How to resolve it?
When n is zero, you never reach a return. You need a return after the loop. Returning -1 might be the sensible choice in that situation. (Also, the return in the loop is misplaced...)
It means that int LinearSearch() is expected to return an int but there are code paths where that does not happen. For instance, if n == 0. You fix this by adding a return statement with an appropriate value on that code path. It's probably an error that you have the return within the for() loop as this means you get at most one iteration. Maybe this is what you want?
int LinearSearch()
{
int ans=-1;
cout << "Enter the Size of the array: \n";
int n;
cin >> n;
cout << "Enter the array elements: \n";
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int key;
cout << "Enter the key: \n";
cin >> key;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
cout << "the " << key << " is found at index " << i << endl;
ans = i;
break;
}
}
return ans;
}
Like others have mentioned, the warning indicates one of your code path has no return value. In LinearSearch after the for loop a return is missing. You can use -1 to return when a key match is not found or better still is if your C++ compiler supports C++17 or higher standard then I would suggest using std::optional and to return a "no value" to use std::nullopt and return the "ans" when you actually find the key.
Please look at the code below for a sample implementation.
#include <optional>
using namespace std;
std::optional<int> LinearSearch()
{
int ans;
cout << "Enter the Size of the array: \n";
int n;
cin >> n;
cout << "Enter the array elements: \n";
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int key;
cout << "Enter the key: \n";
cin >> key;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
cout << "the " << key << " is found at index " << i << endl;
return ans;
}
}
return std::nullopt;
}
int main()
{
while (1)
{
cout << "\t Main Menu\n";
cout << "1. For Linear Search\n";
cout << "2. For Binary Search\n";
cout << "3. For First and last Occurence\n";
int ch;
cout << "Enter the choice: \n";
cin >> ch;
switch (ch)
{
case 1:{
auto res = LinearSearch();
if (res) cout<< *res;
else cout << "key not found";
}
break;
case 2:
break;
case 3:
break;
default:
cout << "Invalid Choice OOps!! ";
break;
}
}
return 0;
}
Program should begin with asking , whether to restock or continue with the current stock. The case 1 ( restock ) works perfectly , however the second case , to continue with the previous stock , returns zeros always if any of the products is zeroed.
In the textfile I have:
Milk: 10
Eggs: 2
Water: 7
Burrito: 10
Bread: 12
exit
How can i fix that ?
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
string productName[5] = { "Milk", "Eggs", "Water", "Burrito", "Bread" };
//int productAmount[5] = { 5,12,10,4,7};
int productAmount[5];
int productPick;
int defaultPick;
int productBuy;
fstream productFile; //we create file
void loadFromFile()
{
productFile.open("productsfile.txt", ios::in);
if (productFile.good() == false)
{
cout << "Unable to load the file. Try again later." << endl;
productFile.close();
exit(0);
}
else
{
ifstream productFile("productsfile.txt");
if (productFile.is_open())
{
cout << "How may I help you?" << endl;
string line;
while (getline(productFile, line))
{
// using printf() in all tests for consistency
cout << line.c_str() << endl;
}
productFile.close();
}
}
}
void saveToFile() //this function saves in the text file the data we've globally declared. It is used only if you want to declare new variables.
{
productFile.open("productsfile.txt", ios::out);
for (int i = 0; i < 5; i++)
{
productFile << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
productFile << "6. Exit" << endl;
productFile.close();
}
void askIfDefault()
{
cout << "Do you want to come back to default stock?" << endl;
cout << "1. Yes " << "2. No " << endl;
cin >> defaultPick;
switch (defaultPick)
{
case 1:
for (int i = 0;i < 5;i++)
{
productAmount[i] = 10;
}
saveToFile();
loadFromFile();
break;
case 2:
loadFromFile();
break;
default:
cout << "I don't understand." << endl;
exit(0);
break;
}
}
void productCheck()
{
if (productAmount[productPick - 1] <= 0 || productAmount[productPick - 1] < productBuy)
{
cout << "Unfortunately we have no more " << productName[productPick - 1] << " in stock. Please choose other product from the list below: " << endl;
productAmount[productPick - 1] = 0;
}
else
{
productAmount[productPick - 1] -= productBuy;
}
}
void listOfProducts()
{
cout << "How may I help you?" << endl;
for (int i = 0; i < 5; i++)
{
cout << i + 1 << ". " << productName[i] << ": " << productAmount[i] << endl;
}
cout << "6. Exit" << endl;
}
void order()
{
cin >> productPick;
switch (productPick)
{
case 1:
cout << "How many bottles?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 2:
cout << "How many cartons?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 3:
cout << "How many multi-packs?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 4:
cout << "How many portions?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 5:
cout << "How many batches?" << endl;
cin >> productBuy;
{
productCheck();
saveToFile();
}
break;
case 6:
cout << "See you soon!" << endl;
saveToFile();
system("pause");
break;
case 666:
cout << "You cannot use the secret magic spells here." << endl;
saveToFile();
exit(0);
break;
default:
cout << "Please pick the existing product: " << endl;
saveToFile();
order();
break;
}
}
int main()
{
askIfDefault();
order();
cout << endl;
while (true && productPick != 6)
{
listOfProducts();
order();
saveToFile();
cout << endl;
}
return 0;
}
Maybe unless declaring one global fsteam productFile, try to declare the it inside each of both functions that are using it: 'loadFromFile()' and 'saveToFile()' respectively. At the beginning of them. It should be fine then.
Let me make a few additional suggestions about your code - because it's a bit difficult to follow:
Choose function names which reflect what the function does - and don't do anything in a function which exceeds what its name indicates. For example, if you wrote a function called ask_whether_to_restock() - that function should ask the question, and perhaps even get the answer , but not actually restock even if the answer was "yes" - nor write anything to files. Even reading information from a file is a bit excessive.
If you need to do more in a function than its name suggests - write another function for the extra work, and yet another function which calls each of the first two and combines what they do. For example, determine_whether_to_restock() could call read_current_stock_state() which reads from a file, and also print_stock_state() and, say, get_user_restocking_choice().
Try to avoid global variables. Prefer passing each function those variables which it needs to use (or references/pointers to them if necessary).
Don't Repeat Yourself (DRI): Instead of your repetitive switch(produtPick) statement - try writing something using the following:
cout << "How many " << unit_name_plural[productPick] << "?" << endl;
with an additional array of strings with "bottles", "cans", "portions" etc.
This is what I have so far. I am trying to edit a dynamically allocated array in C++, however, when the for loop runs, it is skipping over the first item. I need it to get all of the items. Any help is appreciated. Thanks in advance.
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Declare Variables
int userChoice = 0;
int numItems = 0;
cout << "How many items will be on your list? ";
cin >> numItems;
string *list = new string[numItems];
// Give the user some options
cout << "1. Add Item" << endl;
cout << "2. Remove Item" << endl;
cout << "3. Sort Items" << endl;
cout << "4. Exit" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
cout << endl;
// Perform the operation
switch(userChoice)
{
case 1:
{
cin.clear(); // Remove new line from cin
for(int i = 0; i < numItems; i++)
{
cout << "Item #" << i + 1 << " --> ";
getline(cin, list[i]);
}
}
break;
case 2:
{
}
break;
case 3:
{
}
break;
case 4:
{
return 0;
}
default:
{
cout << "Error! Invalid Selection" << endl;
}
}
// Output the list
cout << "-------Items-------" << endl
<< *list << endl << endl;
// free memory
delete [] list;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
return 0;
}
It seems odd to me to be using the STL for some things (like string) and then use a standard array to hold the strings. Also, list is a standard type of object in STL, so that is not a great name for a variable. This revised code fixes your issues with ignoring the first line, and also uses a vector instead of doing new and delete.
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
// Declare Variables
int userChoice = 0;
int numItems = 0;
cout << "How many items will be on your myList? ";
cin >> numItems;
cin.ignore ();
vector<string> myList;
while (true)
{
// Give the user some options
cout << "1. Add Item" << endl;
cout << "2. Remove Item" << endl;
cout << "3. Sort Items" << endl;
cout << "4. Exit" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
cin.ignore ();
cout << endl;
// Perform the operation
switch(userChoice)
{
case 1:
{
for(int i = 0; i < numItems; i++)
{
cout << "Item #" << i + 1 << " --> ";
string s;
getline(cin, s);
myList.push_back (s);
}
}
break;
case 2:
{
}
break;
case 3:
{
sort (myList.begin (), myList.end ());
}
break;
case 4:
{
return 0;
}
default:
{
cout << "Error! Invalid Selection" << endl;
}
}
// Output the myList
cout << "-------Items-------" << endl;
copy(myList.begin(), myList.end(), ostream_iterator<string>(cout, "\n"));
} // end of while
}
The project description explicitly says I can't use standard containers, sort functions, or smart pointers
Redone below to not use those things. :)
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
using namespace std;
int myCompare (const void * a, const void * b)
{
if ((*(string *) a) < *(string *) b) return -1;
if ((*(string *) a) > *(string *) b) return 1;
return 0;
}
int main()
{
// Declare Variables
int userChoice = 0;
int numItems = 0;
cout << "How many items will be on your myList? ";
cin >> numItems;
cin.ignore ();
string *myList = new string[numItems];
while (true)
{
// Give the user some options
cout << "1. Add Item" << endl;
cout << "2. Remove Item" << endl;
cout << "3. Sort Items" << endl;
cout << "4. Exit" << endl;
cout << "Enter the number of the operation you wish to perform: ";
cin >> userChoice;
cin.ignore ();
cout << endl;
// Perform the operation
switch(userChoice)
{
case 1:
{
for(int i = 0; i < numItems; i++)
{
cout << "Item #" << i + 1 << " --> ";
getline(cin, myList [i]);
}
}
break;
case 2:
{
}
break;
case 3:
{
qsort (myList, numItems, sizeof (string *), myCompare);
}
break;
case 4:
{
delete [] myList;
return 0;
}
default:
{
cout << "Error! Invalid Selection" << endl;
}
}
// Output the myList
cout << "-------Items-------" << endl;
for(int i = 0; i < numItems; i++)
cout << myList [i] << endl;
} // end of while
}
The for loop isn't skipping the first element. The first element is just a an empty line.
Because the following clears the error flags.
cin.clear(); // Remove new line from cin --> No!!!!
If you want to skip until the new line you have to use ignore() instead.
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // this removes until newline from cin !
I've been trying to write a short program allowing the user to add entries to a "database", listing the entries they have put in, and the ability to clear all the entries without ending the program. Here's what i've got
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
struct BIRTH
{int month; int year;};
struct ID
{string name; bool vip; float score;
struct BIRTH date;} ;
int main(int argc, char** argv) {
ID **ptrarr;
ptrarr = new ID * [10];
for (int r=0; r<10; r++)
{ptrarr[r] = new ID[1] ;}
int counter = 0;
while(counter<100){
cout << "Type add to create a new entry" << endl;
cout << "Type list to see all entries" << endl;
cout << "Type clear to delete all entries" << endl;
cout << "Type exit to terminate" << endl;
string command = "0";
getline (cin,command);
if(command=="add")
{
cout << "Enter name" << endl;
getline (cin,ptrarr[counter][1].name);
cout << "VIP? 1 for yes, 0 for no" << endl;
cin >> ptrarr[counter][1].vip;
cout << "Enter score" << endl;
cin >> ptrarr[counter][1].score;
cout << "Month of birth" << endl;
cin >> ptrarr[counter][1].date.month;
cout << "Year of birth" << endl;
cin >> ptrarr[counter][1].date.year;
counter++;
}
else if(command=="list")
{
for (int i=0; i<counter; i++)
{int n=i+1;
cout << n << " "
<< ptrarr[i][1].name << " ";
if (ptrarr[i][1].vip)
{cout << "VIP ";}
cout << "Score: " << ptrarr[i][1].score << " "
<< "Born: " << ptrarr[i][1].date.month << "/" << ptrarr[i][1].date.year << endl;
}
}
else if(command=="clear")
{delete[] ptrarr;
cout << "Entries cleared" << endl;}
else if(command=="exit")
{return 0;}
else
cout << "try again" << endl;
}
return 0;
}
Now here's the deal: the following code successfully compiles, but when I type in the "add" command, the program crashes (achievement unlocked, didn't think it's possible to obtain with such a short code). The most important thing is that the array is made of a multitype structure and that the "clear" command wipes out all the entries in the array.
NOTE: I understand that there are thousand better ways to write this piece of code, but I'm writing it to practice the things I have covered so far regarding C++. So unless it is absolutely necessary for the code to run, please do not introduce any new gimmicks =)
Replace all ptrarr[counter][1] with ptrarr[counter][0] fixes the problem.
Further advices:
I. This code has redundancy:
ID **ptrarr;
ptrarr = new ID * [10];
for (int r=0; r<10; r++)
{ptrarr[r] = new ID[1] ;}
Replace it with:
ID *ptrarr;
ptrarr = new ID [10];
Then you do not need extra [0] at the end of each ptrarr[counter]
II. functions make your code more readable:
if(command=="add")
add();
else if(command=="list")
list();
else if(command=="clear")
clear();
else if(command=="exit")
return 0;
else
cout << "try again" << endl;
Then decisions are made in a smaller area (Good practice for large programs.)
III. There is another mistake in your code:
else if(command=="clear")
{delete[] ptrarr;
cout << "Entries cleared" << endl;}
Here you should reset the counter. Also if you regard my point (I) this part is fine. Otherwise, if you use new with a for loop, I am afraid that you need to delete with a for loop too. Merely removing the root of the array tree brings you memory leak!
Also, if you cleared the list by delete, wont you need to store data in the list anymore? Using delete in linked lists is a good idea, but it does not apply here. Just reseting the counter does the job and it does not show IDs in the list anymore. The for inside the list does only count up to the counter.
If you exit the program don't you free the memory?
I say
delete [] ptrarr;
is good for being at exit.
You are creating an an array of pointers, each one of which points to one element:
ptrarr[r] = new ID[1] ;
The maximum index that you can use with ptrarr[r] is 0. Since you are using ptrarr[counter][1], you are accessing memory that is out of bounds. This leads to undefined behavior. Crashing is one such undefined behavior.
There are other issues with your code that you may want to fix.
More out of bounds memory access
You are using:
int counter = 0;
while(counter<100){
...
getline (cin,ptrarr[counter][1].name);
That is again going to lead to undefined behavior if counter > 10 since you allocated only 10 pointers for ptrarr.
Deleting the contents
You are using:
else if(command=="clear")
{
delete[] ptrarr;
cout << "Entries cleared" << endl;
}
There are couple of problems with this:
You have memory leak. You never call delete [] on what ptrarr[0] - ptrarr[9] point to. You'll have to use:
else if(command=="clear")
{
for ( int i = 0; i < 10; ++i )
{
delete [] ptrarr[i];
}
delete[] ptrarr;
cout << "Entries cleared" << endl;
}
Remember that every allocation must have a corresponding deallocation. Otherwise, you are leaking memory.
Once you call delete [] ptrarr;, it points to dangling memory. I don't see any code that reallocates memory for ptrarr while you continue to use it.
You need to reallocate memory and reset counter to 0 when the user chooses "clear".
My suggestion
You don't two levels of pointers. You just need something like:
int const MAX_ITEMS = 100;
ID* IDarr = new ID[MAX_ITEMS];
Instead of ptrarr[counter][1], use IDarr[counter].
Use MAX_ITEMS in the expression of the while statement instead of the magic number 100.
int counter = 0;
while(counter<MAX_ITEMS){
When processing "clear", you don't need to deallocate or allocate memory. Just reset counter.
else if(command=="clear")
{
counter = 0;
cout << "Entries cleared" << endl;
}
Make sure to deallocate memory before returning from main.
Here's the complete main function with the changes:
int main(int argc, char** argv) {
const int MAX_ITEMS = 100;
ID* IDarr = new ID[MAX_ITEMS];
int counter = 0;
while(counter < MAX_ITEMS){
cout << "Type add to create a new entry" << endl;
cout << "Type list to see all entries" << endl;
cout << "Type clear to delete all entries" << endl;
cout << "Type exit to terminate" << endl;
string command = "0";
getline (cin,command);
if(command=="add")
{
cout << "Enter name" << endl;
getline (cin, IDarr[counter].name);
cout << "VIP? 1 for yes, 0 for no" << endl;
cin >> IDarr[counter].vip;
cout << "Enter score" << endl;
cin >> IDarr[counter].score;
cout << "Month of birth" << endl;
cin >> IDarr[counter].date.month;
cout << "Year of birth" << endl;
cin >> IDarr[counter].date.year;
counter++;
}
else if(command=="list")
{
for (int i=0; i<counter; i++)
{
int n=i+1;
cout << n << " " << IDarr[i].name << " ";
if (IDarr[i].vip)
{
cout << "VIP ";
}
cout
<< "Score: " << IDarr[i].score << " "
<< "Born: " << IDarr[i].date.month << "/" << IDarr[i].date.year << endl;
}
}
else if(command=="clear")
{
counter = 0;
cout << "Entries cleared" << endl;
}
else if(command=="exit")
{
// Don't use return 0;
// Just break out of the while loop so that memory
// can be deallocated at the end of this function.
break;
}
else
cout << "try again" << endl;
}
delete [] IDarr;
return 0;
}
Array indices start at 0.
ptrarr[counter][1] refers to the second element of ptrarr[counter]. ptrarr[counter] points to an array of one element.
try this :
if(command=="add") {
cout << "Enter name" << endl;
getline (cin,ptrarr[counter][0].name);
cout << "VIP? 1 for yes, 0 for no" << endl;
cin >> ptrarr[counter][0].vip;
cout << "Enter score" << endl;
cin >> ptrarr[counter][0].score;
cout << "Month of birth" << endl;
cin >> ptrarr[counter][0].date.month;
cout << "Year of birth" << endl;
cin >> ptrarr[counter][0].date.year;
counter++;
}
else if(command=="list") {
for (int i=0; i<counter; i++){
int n=i+1;
cout << n << " "<< ptrarr[i][0].name << " ";
if (ptrarr[i][0].vip){
cout << "VIP ";
}
cout << "Score: " << ptrarr[i][0].score << " "
<< "Born: " << ptrarr[i][0].date.month << "/" << ptrarr[i][0].date.year << endl;
}
}
Conclusion :
Just as you initialized counter with 0 you should have used 0 index to access the first element;
Same goes while listing.
Arrays are 0 index based.
Increase the inventory to be 10 items. DONE!!!
Create a for loop that asks the user to input the initial items in the inventory.DONE!!!
After the for loop create a minor story where the healer changes two items (i.e. items 4 and 8).What I want is to SWAP an item for another item ie would you like to trade your {[item] for [item2] y or n
Sort the inventory in alphabetical order. You can use your own sort if you want, but here is a bubble sort algorithm:
// A simple inventory program using a struct to store data
// in an array.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
// define a data structure
struct InventoryRecord
{
string name; // inventory item name
int qty; // how many are in stock
double value; // the value
};
// const for the max size of the record array
const int MAX_SIZE = 9;
// function prototypes
void addData(InventoryRecord list[], int& size);
void dispData(const InventoryRecord list[], int size);
void remData( const InventoryRecord list[], int size);
void saveFile(const InventoryRecord list[], int size);
void openFile(InventoryRecord list[], int& size);
char getMenuResponse();
int main(int argc, char *argv[])
{
InventoryRecord recList[MAX_SIZE];
int numOfRecs = 0;
bool run = true;
do
{
cout << "Hero's Inventory - " << numOfRecs << " items in your bag" << endl;
switch ( getMenuResponse() )
{
case 'A': addData(recList, numOfRecs); break;
case 'D': dispData(recList, numOfRecs); break;
case 'R': remData(recList, numOfRecs); break;
case 'O': openFile(recList, numOfRecs); break;
case 'S': saveFile(recList, numOfRecs); break;
case 'Q': run = false; break;
default : cout << "That is NOT a valid choice" << endl;
}
} while (run);
cout << endl << "Program Terminated" << endl;
// system("PAUSE"); // Program exits immediatly upon "Quit" if commented out
return EXIT_SUCCESS;
}
// Task: Allow data entry of one inventory item
// Accepts: References to the inventory array and its size
// Returns: Nothing
// Modifies: The array and size 'actual parameter'
// NOTE: Could be modified to allow entry of more than one item
void addData(InventoryRecord list[], int& size)
{
InventoryRecord tmp; // declare a temp item that we will load before putting in the array
char response;
char str[256]; // needed for cin.getline; we are going to use a char array
if (size < MAX_SIZE) {
system("cls");
cout << "Please enter 10 items helpful to your quest! " << endl;
cout << "Enter item: " << endl << endl;
cout << "Name: ";
// Get up to 256 characters from the keyboard including white space.
// Stop reading if encounter the \n first. If there's any chance of
// more than 256 characters you will have to clean up cin with
// cin.ignore before the next input.
cin.getline(str, 256, '\n'); // for char arrays; different from the other getline
tmp.name = str;
cout << "Quantity: ";
cin >> tmp.qty;
cout << "Value: ";
cin >> tmp.value;
cout << endl;
// see if this record should be added to the array
cout << "Add to inventory? (y/n) ";
cin >> response;
if (toupper(response) == 'Y')
list[size++] = tmp;
} else {
cout << "Inventory is full; cannot enter more units." << endl;
system("pause");
}
system("cls");
}
void dispData(const InventoryRecord list[], int size)
{
system("cls");
double cost = 0;
if(size < 1) {
cout << "Nothing to display" << endl;
} else {
cout << "All Items in your Bag" << endl << endl;
cout << fixed << setprecision(2);
cout << "Item Name Qty Value" << endl;
cout << "~~~~~~~~~~~~~~~~~~" << endl;
cout << left;
for (int i = 0; i < size; i++) {
cout << setw(21) << list[i].name << right
<< setw(4) << list[i].qty
<< setw(10) << list[i].value << left << endl;
cost = cost + list[i].value * list[i].qty;
}
cout << "~~~~~~~~~~~~~~~~~~~" << endl;
cout << right << setw(3) << size;
cout << " items listed";
cout << right << setw(19) << cost << endl << endl;
}
system("PAUSE");
system("cls");
}
void remData(const InventoryRecord list[], int size) {
system("cls");
cout <<"Enter Item you wish to remove from your inventory: " << endl;// This is being displayed so user can see items in the inventory
double cost = 0;
if(size < 1) {
cout << "Nothing to display" << endl;
} else {
cout << "All Items in your Bag" << endl << endl;
cout << fixed << setprecision(2);
cout << "Item Name Qty Value" << endl;// It is not displaying right the alignment is off
cout << "~~~~~~~~~~~~~~~~~~" << endl;
cout <<"Item Name: ";/* from here I do not know what to do! What I want is have use type the item name they want removed
also display an error if they enter an item wrong*/
cout << left;
for (int i = 0; i < size; i++) {
cout << setw(21) << list[i].name << right
<< setw(4) << list[i].qty
<< setw(10) << list[i].value << left << endl;
cost = cost + list[i].value * list[i].qty;
}
cout << "~~~~~~~~~~~~~~~~~~~" << endl;
cout << right << setw(3) << size;
cout << " items listed";
cout << right << setw(19) << cost << endl << endl;
}}
// Save records to disc
void saveFile(const InventoryRecord list[], int size) {
ofstream outfi("Inventory.txt");
// make sure the file stream is open before doing IO
if (!outfi.fail()) {
system("cls");
cout << "Saving inventory to the disc ";
for(int i = 0; i < size; i++) {
outfi << list[i].name << ';'
<< list[i].qty << ';'
<< list[i].value;
// Start a new line after all but the last record
// Simplifies reading the file as EOF is at end of last line
if (i < size-1) outfi << endl;
}
cout << endl << size << " records writen to the disc." << endl;
outfi.close();
system("PAUSE");
system("cls");
}
else {
cout << "ERROR: problem with file" << endl;
system("PAUSE");
system("cls");
}
}
// Open file and load array
void openFile(InventoryRecord list[], int& size)
{
ifstream infi("Inventory.txt");
string str;
stringstream strstrm;
// make sure the file stream is open before doing IO
if (!infi.fail()) {
system("cls");
cout << "Reading inventory from the disc ";
size = 0; // overwrite any existing records
while(!infi.eof() && size < MAX_SIZE) {
// get and store the name
getline(infi, str, ';');
list[size].name = str;
// get, convert and store the quantity
getline(infi, str, ';');
strstrm.str(""); strstrm.clear(); // empty and clear the stringstream
strstrm << str;
strstrm >> list[size].qty;
// get, convert and store the cost
getline(infi, str);
strstrm.str(""); strstrm.clear(); // empty and clear the stringstream
strstrm << str;
strstrm >> list[size++].value;
}
cout << endl << size << " records read from the disc." << endl;
system("PAUSE");
system("cls");
}
else { // something went wrong with opening the file
cout << "ERROR: problem with file" << endl;
system("PAUSE");
system("cls");
}
}
char getMenuResponse()
// Task: Put the menu on screen and get a response
// Accepts: Nothing
// Returns: The users response
// Modifies: Nothing
// NOTE: Characters are far more intuitive at the command
// line than numbers; avoid using numbers.
{
char response;
cout << endl << "Make your selection" << endl
<< "(A)dd Items, (D)isplay Items, (R)emove items, (O)pen File, (S)ave File, (Q)uit" << endl
<< "> ";
cin >> response;
cin.ignore(256, '\n');
// clean-up up to 256 chars including the delimiter specified (\n, the endl)
// OR stop when the \n is encountered after removing it.
return toupper(response);
}
To remove an element from your inventory, you just need to move all elements after the removed element one position forward. Once that is done, you also need to reduce the lengthy by one. For example, to remove the elements at the position index from an array array with currently length elements you could use
if (index < length) {
std::copy(array + index + 1, array + length, array + index);
++length;
}
There are essentially two ways to remove the element, the easiest is swap the element which you want to delete with the last one and resize the list:
void deleteElem(Data[] list, int & listLength, int ix) {
if (ix < listLength - 1) {
list[ix] = list[listLength - 1];
}
--listLength;
}
The second solution is memmove everthing after the to deleting element one to the left:
void deleteElem(Data[] list, int & listLength, int ix) {
memmove(list[ix], list[ix + 1], (listLength - ix - 1) * sizeof(Data));
--listLength;
}
EDIT: There was an error in the length for memmove, always the same. You should read the documentation.