how to store input in a dynamic array? - c++

So I am trying to make a program that stores user input into a dynamic array but I cant do it right. When I try to put a number let us say 1, and I want to try again then I want to view history, the only thing that shows up is the last number I have input. And sometimes there is a large number sowing up like 1214098101909279242 like that.
Here is my code:
#include<iostream>
using namespace std;
int main(){
const int size = 20;
int *num = new int[size];
char answer;
while(true){
cout<<"ENTER NUMBER: \n";
cin>>*num;
cout<<"TRY AGAIN? ";
cin>>answer;
switch(answer){
case 'y':
num[size+1];
system("cls");
break;
default:
cout<<"INPUT HISTORY: \n";
for(int i=0;i<=size;i++){
cout<<num[i];
}
}
}
return 0;
}

I have two major issues with your code:
There is no need for dynamic allocation in this case, since size is a const value (and can be defined as constexpr, which is better).
instead of using the standard containers (such as std::array (for constant size array) or std::vector (for dynamically expanding array)) you use a plain pointer array, which is ill-advised, and in this case can cause memory leak (for example, if you move this code into an utility function, since you never delete the memory of num array!), you should use std::unique_ptr instead! (and better read about the RAII idiom).
Spacing and indentation - your code should be readable to other coders as well.
About your code, the original code have the following line:
cin >> *num
which means put the value in stdin into the FIRST position of num. In both C/C++, arrays are just pointers to the first address of memory that was allocated for the array. In order to access the other items, you need to use the operator[] or use pointer arithmetic with the operator* (for example:
cin >> *(num + count)
will get the item at position count). Also, as pointed above, there is no safety measure for disallowing writing to an invalid memory that you can count on. Therefore, you should use the std containers which enforce index safety.
Just for reference, here is the code I would have wrote to get the same functionality:
int main() {
constexpr size_t SIZE = 20;
std::array<int, SIZE> arr;
arr.fill(0);
int last_filled_position = 0;
bool cont = true;
while (cont)
{
int val;
char answer;
cout << "ENTER NUMBER:" << std::endl;
cin >> val;
cout<<"TRY AGAIN? Yes/Print/Stop";
cin >> answer;
arr.at(last_filled_position++) = val;
switch (answer)
{
case 'y':
system("cls");
break;
case 'p':
cout << "INPUT HISTORY: " << std::endl;
for (int val: arr) // With more complex types, you should use const auto&
{
cout << val << ", ";
}
cout << endl;
break;
case 's':
cont = false;
cout << "STOPPING";
break;
}
}
return 0;
}

So I have change the code a little bit. Is my code valid for some reason? because it works fine now. I can input numbers and when i view all the numbers, it works fine.
#include<iostream>
using namespace std;
int main(){
const int size = 20;
int *num = new int[size];
char answer;
int count = 1;
while(true){
cout<<"ENTER NUMBER: \n";
cin>>num[count-1];
cout<<"TRY AGAIN? ";
cin>>answer;
switch(answer){
case 'y':
count++;
system("cls");
break;
default:
cout<<"INPUT HISTORY: \n";
for(int i=0;i<=count-1;i++){
cout<<num[i]<<endl;
}
count++;
}
}
return 0;
}

Related

Taking Input to Arrays Issue

I'm creating a console timetable application in which you can create a timetable, change it, and delete it. I'm on the stage of taking the input for the calculator. However, when I run the code, as soon as I finish taking the input, the window just closes. Here is the code:
int input()
{
int numberOfElements;
cout << "How many items do you want in your timetable? ";
cin >> numberOfElements;
char* itemArray[numberOfElements] = {};
for (int i = 1; i <= numberOfElements; i++)
{
cout << "Please enter a session: ";
cin >> itemArray[i];
}
for (int i = 0; i < numberOfElements; i++)
{
cout << itemArray[i] << "\n";
}
return 0;
}
There is some code in the main function as well, but it's irrelevant (only to find out for what day it is). I want you to have a look at the first for loop in the code, where I take in input. When running this code (in a separate window altogether), it closes as soon as I give in the input. Even if I say that I want 3 sessions (or any number), it closes right after I input the first session. In case you were wondering, I already tried replacing
char* itemArray[numberOfElements] = {};
with
char* itemArray[numberOfElements];
Just in case it's useful to anyone, I'm using the MinGW compiler.
Thanks.
In Standard C++ the size of an array must be a compile time constant. So take for example the following statements in your program:
int numberOfElements;
cout << "How many items do you want in your timetable? ";
cin >> numberOfElements;
char* itemArray[numberOfElements] = {};//not standard C++
The statement char* itemArray[numberOfElements] = {}; is not standard C++ because numberOfElements is not a constant expression.
Additionally, you're going out of bounds of the array because of the <= in the for loop instead of <. This leads to undefined behavior.
Better would be to use std::vector<std::string> as shown below:
#include <iostream>
#include<vector>
#include <string>
int main()
{
int numberOfElements;
std::cout << "How many items do you want in your timetable? ";
std::cin >> numberOfElements;
std::vector<std::string> arr(numberOfElements); //create vector of size numberOfElements
for (std::string &element: arr)
{
std::cout << "Please enter the element: ";
std::cin >> element;
}
for (const std::string& element: arr)
{
std::cout << element << "\n";
}
}
Demo.

Having problem in working with insert, delete and search in an string array at the same time

I was trying to implement insert, delete and linear search in an string type array in the same code. Delete and Linear search works fine here, but insertion is not running perfectly.
Here is the main function of my code.
#include<iostream>
#include <stdlib.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
int main(int argc, char ** argv)
{
int siz;
cout<<"How many elements:";
cin>>siz;
string student[siz];
for(int i=0; i<siz; i++)
{
cin>>student[i];
}
cout<<"Array:";
for(int i=0; i<siz; i++)
cout<<student[i]<<endl;
int choice;
cout <<"Enter your choice :";
cin>>choice;
switch(choice)
{
case 0:
exit(0);
break;
case 1:
st_insert(student,siz);
break;
case 2:
st_delete(student,siz);
break;
case 3:
st_search(student,siz);
break;
case 4:
cout<<"All elements\n:";
for(int i=0; i<siz; i++)
cout<<student[i]<<endl;
break;
default:
cout<<"Wrong choice please try again !!!";
}
return 0;
}
The insert function is
void st_insert(string demo[], int siz)
{
int pos;
cout<<"Enter a position number to insert:";
cin>>pos;
string item;
cout<<"Enter a new Element :";
cin>>item;
cout<<"After Inserting "<<item<<", the updated list is: "<<endl;
for (int i=siz-1; i>=pos; i--)
{
demo[i+1] = demo[i];
}
demo[pos] = item;
for (int i=0; i<siz+1; i++)
cout<<"\t"<<demo[i]<<endl;
}
Sample Output if I want to insert an item
Yes, there is a solution. Don't use non-standard VLAs and don't use Plain-Old Arrays that provide no bounds checking. The solution is to use a vector of strings, e.g. std::vector<std::string>. That way you can add or replace any element you like and the memory is handled automatically.
For example, let's just take a vector of strings initialized with four strings:
std::vector<std::string> student { "my", "dog", "has", "fleas" };
Now student.size() will tell you how many strings are contained in the vector and you can replace (with bounds checking) with student.at(pos) = "new string";
You can list all elements in your vector using a range-based for loop, e.g.
std::cout << "Array:\n\n";
for (const auto& s : student)
std::cout << s << '\n';
Since the vector of strings student contains all the information you will need to either replace an existing element or add a new element at the end, your function (which must be of a type to indicate success/failure of the operation) could be written to take a single parameter -- a reference to your vector of strings, e.g.:
bool st_insert(std::vector<std::string>& demo)
{
size_t pos;
std::string item {};
std::cout << "Enter a position number to insert: ";
if (!(std::cin >> pos))
return false;
std::cout << "Enter a new Element: ";
if (!(std::cin >> item))
return false;
if (pos >= demo.size())
demo.push_back(item);
else
demo.at(pos) = item;
std::cout << "\nAfter Inserting \""<< item <<"\", the updated list is:\n\n";
for (const auto& s : demo)
std::cout << s << '\n';
return true;
}
If you want a compilable example, with 0-exit or 1-st_insert as your menu choices, you could do:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
bool st_insert(std::vector<std::string>& demo)
{
size_t pos;
std::string item {};
std::cout << "Enter a position number to insert: ";
if (!(std::cin >> pos))
return false;
std::cout << "Enter a new Element: ";
if (!(std::cin >> item))
return false;
if (pos >= demo.size())
demo.push_back(item);
else
demo.at(pos) = item;
std::cout << "\nAfter Inserting \""<< item <<"\", the updated list is:\n\n";
for (const auto& s : demo)
std::cout << s << '\n';
return true;
}
int main (void)
{
int choice;
std::string tmp;
std::vector<std::string> student { "my", "dog", "has", "fleas" };
std::cout << "Array:\n\n";
for (const auto& s : student)
std::cout << s << '\n';
std:: cout << "\nEnter menu choice: ";
if (!(std::cin >> choice)) {
std::cerr << "error: invalid integer value - choice.\n";
return 1;
}
switch(choice)
{
case 0:
exit(0);
break;
case 1:
if (!st_insert (student))
std::cerr << "error: unable to insert element.\n";
break;
default:
std::cout << "Wrong choice please try again !!!\n";
}
return 0;
}
Example Use/Output
Replace Exmaple:
$ ./bin/insert_str_item
Array:
my
dog
has
fleas
Enter menu choice: 1
Enter a position number to insert: 1
Enter a new Element: cat
After Inserting "cat", the updated list is:
my
cat
has
fleas
Add Example:
$ ./bin/insert_str_item
Array:
my
dog
has
fleas
Enter menu choice: 1
Enter a position number to insert: 40
Enter a new Element: now
After Inserting "now", the updated list is:
my
dog
has
fleas
now
(note: the st_insert() function was written so if the requested pos for the new string exceeds what the next string in the vector would be, it is simply added as the next string and the invalid position is discarded)
Now when you go to take input for your vector of strings, it is quite simple. just read your input into a temporary string and use the .push_back() member function to add the string to your vector of strings, e.g.
std::string tmp {};
std::cout << "enter a string: ";
if (std::cin >> tmp)
student.push_back(tmp);
(note: you must validate every user input before you use the value)
Adding Taking siz New Elements
From your example, if you did want to specify the number of new strings to enter, you could adjust the program as follows:
int main (void)
{
int choice;
size_t siz;
std::string tmp;
std::vector<std::string> student { "my", "dog", "has", "fleas" };
std::cout << "There are currently " << student.size() << " elements:\n\n";
for (const auto& s : student)
std::cout << s << '\n';
std::cout << "\nHow many elements would you like to add? ";
if (!(std::cin >> siz)) {
std::cerr << "error: invalid size-type input.\n";
return 1;
}
for (size_t i = 0; i < siz; i++) {
std::cout << "student[" << student.size() << "]: ";
if (std::cin >> tmp)
student.push_back(tmp);
}
std::cout << "\nCurrent strings:\n\n";
for (const auto& s : student)
std::cout << s << '\n';
std:: cout << "\nEnter menu choice: ";
if (!(std::cin >> choice)) {
std::cerr << "error: invalid integer value - choice.\n";
return 1;
}
switch(choice)
{
case 0:
exit(0);
break;
case 1:
if (!st_insert (student))
std::cerr << "error: unable to insert element.\n";
break;
default:
std::cout << "Wrong choice please try again !!!\n";
}
return 0;
}
Example Use/Output
$ ./bin/insert_str_item
There are currently 4 elements:
my
dog
has
fleas
How many elements would you like to add? 4
student[4]: my
student[5]: cat
student[6]: has
student[7]: none
Current strings:
my
dog
has
fleas
my
cat
has
none
Enter menu choice: 1
Enter a position number to insert: 5
Enter a new Element: frog
After Inserting "frog", the updated list is:
my
dog
has
fleas
my
frog
has
none
You will want to see std::vector and std::basic::string for full details of the use of std::vector and std::string. Also see: Why is “using namespace std;” considered bad practice? and C++: “std::endl” vs “\n”.
Look things over and let me know if you have further questions.
As rightly said by some authors , what is required by you should not be done by fixed memory allocation , instead dynamic memory allocation (example : vectors in c++) should be used. However since you wanted to try the fixed one still, you can do the following :
Declare a string array of a larger size, instead of the user input (siz). Let's say it to be of predefined size 1000. (You can notify user to have a array of size to be less).
Declare the siz variable as global and not local. Because when you come after doing any insertion / deletion operation your size should be more / less than it previously was.But if you are using it as local then the changes would not be reflected because of call by value.
EDITED code:
#include<iostream>
#include <stdlib.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int siz=0;
void st_insert(string demo[])
{
int pos;
cout<<"Enter a position number to insert:";
cin>>pos;
string item;
cout<<"Enter a new Element :";
cin>>item;
cout<<"After Inserting "<<item<<", the updated list is: "<<endl;
for (int i=siz-1; i>=pos; i--)
{
demo[i+1] = demo[i];
}
demo[pos] = item;
siz++;
for (int i=0; i<siz; i++)
cout<<"\t"<<demo[i]<<endl;
}
int main(int argc, char ** argv)
{
cout<<"How many elements:";
cin>>siz;
string student[1005];
for(int i=0; i<siz; i++)
{
cin>>student[i];
}
cout<<"Array:";
for(int i=0; i<siz; i++)
cout<<student[i]<<endl;
int choice;
cout <<"Enter your choice :";
cin>>choice;
switch(choice)
{
case 0:
exit(0);
break;
case 1:
st_insert(student);
break;
case 4:
cout<<"All elements\n:";
for(int i=0; i<siz; i++)
cout<<student[i]<<endl;
break;
default:
cout<<"Wrong choice please try again !!!";
}
return 0;
}
Rest all seems fine to me.
Hope you got it. :)
In C++, arrays have a fixed sized and when passed as parameters what you are actually getting is a pointer to the first element in the array. In you code, you are trying to access demo[i+1] when size equals size-1; this generates an error because you are trying to access a memory location that isn't part of the array (demo[size]). When inserting an element in an array, you need to first allocate a new chunk of memory with the new size, then you copy each element over(including the new value), and finally delete the old chunk of memory which is now unused.

how to store data into dynamic array

I have this program that asks user to enter a number and ask the user if they want to view input history. So i was wondering if my code is correct. I want to know if doing cin>>num[count-1] is correct or is there a correct way to get the data the user inputs. Here it is:
#include<iostream>
using namespace std;
int main(){
const int size = 20;
int *num = new int[size];
char answer;
int count = 1;
while(true){
cout<<"ENTER NUMBER: \n";
cin>>num[count-1];
cout<<"TRY AGAIN? ";
cin>>answer;
switch(answer){
case 'y':
count++;
system("cls");
break;
default:
cout<<"INPUT HISTORY: \n";
for(int i=0;i<=count-1;i++){
cout<<num[i]<<endl;
}
count++;
}
}
delete [] num;
return 0;
}
I want to know is doing cin>>num[count-1]` is correct or is there a correct way to get the data the user inputs.
Your code is a c-style code. You have the std::array and std::vector to help you to write a more secure and clean code. Because your tag in your question is dynamic-arrays I suggest to use the std::vector.
Bellow you can check out your code could be with the replacement.
#include <iostream>
#include <vector>
using namespace std;
int main() {
//int *num = new int[size]; //normally you don't need to use new. Let the c++ manage it for you
vector<int> num;
char answer;
while (true) {
cout << "ENTER NUMBER: \n";
num.emplace_back(); //Create a new element to vector num
cin >> num.back(); //set this new element
cout << "TRY AGAIN? ";
cin >> answer;
if (answer == 'y')
system("cls");
else {
cout<<"INPUT HISTORY: \n";
for (auto& numEle : num) //It will interate over all elements of num
cout<< numEle <<endl;
//break; //Maybe you want to break the loop here
}
}
// delete [] num;
return 0;
}
I will first show you the problems in your code. I put in comments.
Then I will explain you, why your input is wrong. Also the answer from user TheArquitect is wrong and will finally lead to a memory overflow.
Your program will also have a desastrous result.
First see the code:
#include<iostream>
using namespace std; // In C++ we never use this statement. Why? See:
// You will find at least 1000 comments in Stackoverflow
int main() {
const int size = 20; // In C++ we use constexpr for compile time constants
int* num = new int[size]; // In C++ we
// Do not use raw pointers for owned memory
// Do not use new
// Do Not use C-Style arrays
// Generally: std::vector should be used
// Or at least std::unique_ptr and std::make_unique
// Also, this 2 lines are nonesense. It is the same as int num[20];
char answer; // All variables should always be initialized
// Variables should be in the scope, where they are necessary
int count = 1; // YOu could use uniform initialization
// Arrays start with index 0 in C++ (also in C )
while (true) { // You are creating an endless loop with desastrous effect
cout << "ENTER NUMBER: \n";
cin >> num[count - 1]; // No, this will not work. Explanation in text
cout << "TRY AGAIN? ";
cin >> answer; // No, this will not work. Explanation in text
switch (answer) { // Switch with only one case can always be expressed with if elese
case 'y':
count++;
system("cls"); // This is a non portable solution
break;
default:
cout << "INPUT HISTORY: \n";
for (int i = 0; i <= count - 1; i++) { // Nearly Never use <= in for loops
// Use for (int i = 0; i < count; i++)
// Do use ++i insted of i++
cout << num[i] << endl;
}
count++;
} // This is an endless loop. count will always be increased. If greater than 20
// then the memory will be corrupted. This will happen always
}
delete[] num; // Dead code. Will never be invoked
return 0;
}
OK. Now, besides the major bugs and the killing out of bounds problem, here the explanation for the problem with inputting data.
Rule: You must always check, if the input operation worked. For that you can check the state of the stream. Additionally, if you do not consume the input data (because of an erronous input by the user), this data is still in the input buffer. And in the next loop it will be read again (without waiting for new user input). The status of the input stream may still be wrong and it will also not read because of this.
Then the endless loop starts to run without user input and corrupts your memory.
You may check, by simply inputting a letter instead of a number.
How to fix?
Again, you must check the state of the stream after reading. This is usually done in the form:
if (std::cin >> number)
Why does this work? Because: The inserter operator returns a reference to the stream (so std::cin) and the boolean '!' not-operator for the std::istream is overwritten. It will show, if the state of the stream is still ok or not.
OK, understood. Now. What to do in case of error? 2 operations:
Clear all failure bits in the state of the stream --> std::cin.clear()
Eat up everything that is still in the input buffer --> std::cin.ignore()
You could write:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I assume that you are learing C++ in a class and learn about new and delete. As said, you should not use it. But because teacher request this often in the classes, I will show you now a better solution than yours, still using new, but without (most of) the problems.
#include<iostream>
#include <limits>
int main() {
// We want to create a dynamic array with 20 elements
constexpr size_t MaxArraySize{ 20U };
// Allocate a dynamic arry on the heap
int* numberArray = new int[MaxArraySize];
// Read maximum 20 numbers into our dynamic array
for (size_t currentArrayIndex{}; currentArrayIndex < MaxArraySize; ) {
// Inform the user that he should ent now a number
std::cout << "Enter number: \n";
// Read the number and check, if this worked
if (std::cin >> numberArray[currentArrayIndex]) {
// Now ask, if the user wants to continue or stop
std::cout << "Doy you want to enter more numbers? ('y' or 'n'): ";
// Define variable answer and get user input and check, if ok
if (char answer{}; std::cin >> answer) {
// Does the user want to continue?
if ('y' == answer) {
// Yes, continue. Increment array index
++currentArrayIndex;
}
else {
// No, the user does not want to continue. Show the values entered so far
std::cout << "Input History:\n";
for (size_t i{}; i <= currentArrayIndex; ++i) { // NOTE: <= becuase index has not yet been incrementet
std::cout << numberArray[i] << "\n";
}
break; // Stop the for loop and end the program
}
}
else {
// Strange, input of a character did not work. Should not happen. Terminate program
std::cerr << "\n*** Error: Problem with input!\n\n";
break; // Stop the for loop and end the program
}
}
else {
// The user entered someting wrong, or the input did not work for any other reason
// Inform user about problem
std::cerr << "\n*** Error: No number could be read!\n\n";
// Clear error flag and comsume whatever is in the input buffer
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
// Release dynamic allocated memory
delete[] numberArray;
return 0;
}

Super basic code: Why is my loop not breaking?

for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
cout << size;
if(inputnum[i] == '.')
{
break;
}
}
The break breaks the input stream but the size keeps outputting.
The output of size is 012345678910111213...474849.
I tried putting size++ inside the loop but it made no difference. And size afterwards will be equal to 50, which means it went through the full loop.
I forgot to explain that I added the cout << size within the loop to debug/check why it outputted to 50 after the loop even if I only inputted 3 numbers.
I suspect that inputnum is an array of int (or some other numeric type). When you try to input '.', nothing actually goes into inputnum[i] - the cin >> inputnum[i] expression actually fails and puts cin into a failed state.
So, inputnum[i] is not changed when inputting a '.' character, and the break never gets executed.
Here's an slightly modified version of your code in a small, complete program that demonstrates using !cin.good() to break out of the input loop:
#include <iostream>
#include <ostream>
using namespace std;
int main()
{
int inputnum[50];
int size = 0;
for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
if (!cin.good()) {
break;
}
}
cout << "size is " << size << endl;
cout << "And the results are:" << endl;
for (int i = 0; i < size; ++i) {
cout << "inputnum[" << i << "] == " << inputnum[i] << endl;
}
return 0;
}
This program will collect input into the inputnum[] array until it hits EOF or an invalid input.
What is inputnum ? Make sure t's a char[]!! with clang++ this compiles and works perfectly:
#include <iostream>
int main() {
int size = 0;
char inputnum[60];
for(int i=0;i<50;i++,size++) {
std::cin >> inputnum[i];
std::cout << size;
if(inputnum[i] == '.') {
break;
}
}
return 0;
}
(in my case with the following output:)
a
0a
1s
2d
3f
4g
5.
6Argento:Desktop marinos$
Your code seams OK as long as you're testing char against char in your loop and not something else.. Could it be that inputnum is some integral value ? if so, then your test clause will always evaluate to false unless inputnum matches the numerical value '.' is implicitly casted to..
EDIT
Apparently you are indeed trying to put char in a int[]. Try the following:
#include <iostream>
int main() {
using namespace std;
int size = 0;
int inputnum[50];
char inputchar[50];
for(int i=0;i<50;i++,size++) {
cin >> inputchar[i];
inputnum[i] = static_cast<int>(inputchar[i]); // or inputnum[i] = (int)inputchar[i];
cout << size << endl; // add a new line in the end
if(inputchar[i] == '.') break;
}
return 0;
}
Then again this is probably a lab assignment, in a real program I'd never code like this. Tat would depend on the requirements but I'd rather prefer using STL containers and algorithms or stringstreams. And if forced to work at a lower-level C-style, I'd try to figure out to what number '.' translates to (simply by int a = '.'; cout << a;`) and put that number directly in the test clause. Such code however might be simple but is also BAD in my opinion, it's unsafe, implementation specific and not really C++.

c++ program gives an error" the value of 'i' is not initiated"

this code gives an error "i" is not initiated, can anybody help it out ?
the program complies easily. and at the time of running, every switch case works but 2.
#include<iostream>
using namespace std;
const int m=50;
class ITEMS
{
int itemCode[m];
float itemPrice[m];
int count;
public:
void CNT(void)
{
count=0;
}
void getItem(void);
void displaySum(void);
void remove(void);
void displayItems(void);
};
functions used.
void ITEMS :: getItem (void)
{
cout<<"entr itm cod";
cin>> itemCode[count];
cout<<"entr itm cost";
cin>> itemPrice[count];
count++;
}
the problem is here. this function"displaySum (void)" must give an output by summing the prices of all the items
void ITEMS ::displaySum (void)
{
float sum =0;
for (int i; i<count;i++)
sum+=itemPrice[i];
cout<<"\n total value"<< sum<<endl;
}
void ITEMS ::remove (void)
{
int a;
cout<< "entr itm cod";
cin>> a;
for(int i=0; i<count;i++)
if (itemCode[i] == a)
itemPrice[i]=0;
}
void ITEMS :: displayItems(void)
{
cout<< "\n Code price\n";
for(int i=0;i<count;i++)
{
cout<<"\n" << itemCode[i];
cout<<" " << itemPrice[i];
}
cout<< endl;
}
main function. this is here i called all the above functions. using the main function.
int main()
{
ITEMS order;
order.CNT();
int x;
do
{
cout<< "select any opt"
<<"\n 1. add"
<<"\n 2. display total valu"
<<"\n 3. delete an item"
<<"\n 4. display all"
<<"\n 5. quit?
<<"\n number ?";
cin>> x;
switch(x)
{
case 1: order.getItem(); break;
case 2: order.displaySum(); break;
case 3: order.remove(); break;
case 4: order.displayItems(); break;
case 5: break;
default: cout<< "try again";
}
}while(x!=5);
return 0;
}
In displaySum you have:
for (int i; i<count;i++)
sum+=itemPrice[i];
i is not initialized here. That's probably not what you want.
Also, make sure you pay attention to what your compiler tells you. If you are using gcc, for example, you can use the options "-Wall -Werror" which generates warnings for common programming mistakes, and reports them as errors. IMO this is good practice as it forces you to at least look at that spot to see if you actually made a programming error.
I don't know which compiler you're using, but I don't know of a single one that does not provide at least a line number when printing warnings. Use the resources available to you. The compiler almost certainly told you exactly what was wrong and where the error occured. While the expression you used is legal, it is certainly an error.
int i;
does not initialize the local variable, make an experiment and print it, you will see it is filled with previous stack junk. so it probably wont satisfy the for(;;) condition and just never enter the loop
use
int i = 0;
In displaySum you are not initializing variable i, so it contains a garbage value and your loop will behave unpredictably.