C++ values not reading in while loop switch case - c++

All functions have be declared public in my .header file
this is my code:
void menu
{
int option = 0;
//cout menu here//
//getting user input to enter their option of menu
cin>>option;
menuChoice(option);
}
void menuChoice(int option)
{
int kiv = 0;
const int size = 50;
while(option) //option just an int to get input from a menu
{
switch(option)
{
case 1: {
while(kiv<size)
{
//codes here to read user inputs then entry increment
++kiv;
}
//cout<<kiv<<endl; // doesn't work here too , it displays nothing
}break;
case2:{
cout<<kiv<<endl; // displays 0
}break;
}
}
}
i have declared the kiv on top , then increment it in the while loop , however the value stays in the while(option) loop so when i go to case 2 , it suppose to print out the incremented value , but it display 0 , am i going in the correct direction?

This may be the one you looking for
int kiv = 0;
const int size = 50;
void menuChoice(int option);
void getOption()
{
int option = 0;
cin >> option;
menuChoice(option);
}
void menuChoice(int option)
{
switch (option) {
case 1:
while (kiv < size) {
//codes here to read user inputs then entry increment
++kiv;
}
//cout<<kiv<<endl; // doesn't work here too , it displays nothing
break;
case 2:
cout << kiv << endl; // displays 0
break;
}
getOption();
}
void menu()
{
//cout menu here//
//getting user input to enter their option of menu
getOption();
}
int main(int argc, char **argv)
{
menu();
return 0;
}

It's not entirely clear from your example, but I am guessing that each time you process a menuChoice you enter that function, and as a result you re-initialised kiv back to 0 each time.
If that is the case, you probably need to change the type of kiv to
static int kiv = 0;
This will cause kiv to retain its value between invocations.

Related

how to replace a value of a variable inside code from user input?

i am trying to add a developer mode in my program. since duty of car defers every month,i want give my user permission to change every single variables in my program alike duty lccost yen2taka freight
#include <iostream>
using namespace std;
class A
{
public:
int carbid,duty;
void Input()
{
cout<<"please insert the car price you want to bid for(in yen): ";
cin>>carbid;
cout<<"duty of the car: ";
cin>>duty;
}
int Exportcost()
{
int exportcost;
int servicechrg=10;
int freight=20;
exportcost=servicechrg+freight+carbid;
return exportcost;
}
int Yen2taka()
{
int yen2taka;
int taka2dollarrate=10;
int dollar2yen=1;
yen2taka=((Exportcost())/dollar2yen)*taka2dollarrate;
return yen2taka;
}
int Importcost()
{
int importcost;
int lccost=10;
int cnfcost=20;
importcost=lccost+cnfcost;
return importcost;
}
int Totalcosting()
{
int total;
int myprofit=10; //80000
total=myprofit+Importcost()+Yen2taka();
cout<<total;
return total;
}
void summary()
{
cout<<
}
};
int main()
{
x:
A ob;
ob.Input();
ob.Exportcost();
ob.Yen2taka();
ob.Importcost();
ob.Totalcosting();
int ch;
cout<<"press 1 to see the summery of the costing or 2 to restart costing again"<<endl;
cin>>ch;
switch(ch)
{
case 1:
ob.summary();
break;
case 2:
goto x;
}
}
At first, you should collect these parameters in a separate class:
class Configuration // maybe you find a better name...
{
int m_servicechrg = 10; // default
int m_freight = 20;
// ...
public:
int servicechrg() { return m_servicechrg; }
void servicechrg(int value); { /* check some limits? */ m_servicechrg = value; }
int freight() { return m_freight; }
void freight(int value); { /* check some limits? */ m_freight = value; }
// ...
};
// will allow you to do:
// C c; std::cout << c;
ostream& operator<<(ostream& s, Configuration const& c)
{
// which ever formatting is appropriate...
s << c.servicechrg() << ' ' << c.freight();
return s;
}
The setters could alternatively return bool to indicate invalid values.
Now you can use this class within main:
Configuration c;
A a;
int cost = a.exportCost(c); // you'd have to adjust signatures...
int value;
switch(ch)
{
case 4:
if(stc::cin >> freight) // catches invalid user input!
// one ALWAYS should do, otherwise you might end up in
// your program not working any more
{
c.freight(value);
// or, if you have:
if(!c.freight(value))
{
// some appropriate error message
// (it's better not to output in the setter, you are more flexible this
// way – maybe you want different messages at different occasions?)
}
}
else
{
// appropriate error handling
}
break;
default:
// handling invalid user input
// again, you always should; but stream state is not in error state,
// so you just can print appropriate error message
break;
}
See this answer for how to correctly handle stream errors.
If you wonder about the differences in error handling: First case is met if user enters non-numerical input, such as ss, second case, if input is numerical, but out of valid range (77).
Now if you don't want to pass the configuration as parameter all the time, you could make a global variable from (but careful, there are some dangers with global variables, use them as sparely as possible) or implement the singleton pattern.
Side notes: goto can be a fine tool sometimes, but it is a dangerous one (and the label's name x isn't a good one, prefer a name that clearly shows intention, such as REENTRY_POINT, LOOP_START, ...). If you can get along without unreasonable effort, prefer such variants:
bool isRunning = true;
do
{
// ...
case 2:
isRunning = false;
break;
}
while(isRunning);
Sure, an additional variable, an additional check; unfortunately, you cannot use break to exit a (pseudo-) endless loop (for(;;)) (but don't apply this pattern for nested loops, then it gets more and more unreadabla – and ineffcient: bool isExit = false; for(int i = 0; !isExit && i < n; ++i) { for(j = 0; j < n; ++j) { isExit = true; break; } } – see what I mean?). A variant might be:
for(;;)
{
switch(ch)
case 1:
// ...
//break; <- replace
continue;
case 2:
//
break;
} // end of switch
break; // break the surrounding for(;;) loop
}
But that's not really nice either.
A pretty nice variant allowing to exit the loop in the given case, as there isn't anyhting to do afterwards:
for(;;)
{
switch(ch)
{
case 2:
// maybe yet some cleaning up here
return 0;
default:
// ...
break;
}
}
Drawback: The function's exit point possibly is deeply nested inside the code.
There are yet other tricks to allow this pattern, like packing sub-sections of code in a lambda having a return inside and call that one directly. But that now really starts going beyond the scope...
Finally, if you insist on goto, my variant would rather be:
for(;;)
{
switch(ch)
{
case 2:
// ...
goto LOOP_EXIT;
default:
// ...
break;
}
}
LOOP_EXIT:
return 0; // e. g. main
(void)0; // if there isn't anything to do in the function any more
// (labels require an instruction afterwards!)
There won't be a hidden loop now and it is more obvious what you actually are doing. Currently, not really an issue, but if your code grows, the hidden loop gets more and more difficult to spot.
In such cases, I clearly mark the gotos so that another coder can immediately spot the critical code points:
///////////////////////////////////////////////////
// possibly some comment why applying this pattern
goto SOME_LABEL;
///////////////////////////////////////////////////
One could do the same with deeply nested function exit points (return).

Repeat statement for switch case

So I want make the program that can input data many times, for example I choose case 1 again after I use case 1 to input data. Or I choose case 2 many times to see all data as I want.
Mostly said break statement bring the solution. But, when I using break statement after case, the program was terminated. So how I can make repeat switch statement without make terminating program?
If I make this, the switch case happen sequentially. Example, I can input case 1 normally but when I input case 1 again it will go to next case instead case 1 and vice versa until exit case. This is my source code:
#include <iostream>
#pragma hdrstop
using namespace std;
struct ig
{
int id;
string name;
ig *next;
ig *prev;
};
ig *head= NULL;
ig *tail= NULL;
//---------------------------------------------------------------------------
int main(int argc, char** argv)
{
cout<<"+---------------------------------------+"<<endl;
cout<<"| Instagram User Data |"<<endl;
cout<<"+---------------------------------------+"<<endl;
cout<<"|1. Add Instagram ID |"<<endl;
cout<<"|2. Look All Data |"<<endl;
cout<<"|3. Look Previous Data |"<<endl;
cout<<"|4. Look Next Data |"<<endl;
cout<<"|5. Exit |"<<endl;
cout<<"+---------------------------------------+"<<endl;
int choose,l;
cout<<"your choices (1/2/3/4/5): ";cin>>choose;
switch(choose)
{
case 1:
{
cout<<"Input limit : ";cin>>l;
for(int a=1;a<=l;a++)
{
ig *new= new ig;
new->next=NULL;
new->prev=NULL;
cout<<"Entry Number : ";cin>>new->id;
cout<<"Instagram ID : ";cin>>new->name;
cout<<"===================="<<endl;
if(head== NULL)
{
head=new;
tail=new;
}
else
{
new->prev=tail;
tail->next=new;
tail=new;
}
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 2:
{
while(head!= NULL)
{
cout<<head->id<<endl;
cout<<head->name<<endl;
head=head->next;
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 3:
{
if(tail=NULL)
{
ig *show;
show=head;
while(show!= NULL)
{
cout<<head->id<<endl;
cout<<head->name<<endl;
head=head->prev;
}
}
else
{
cout<<"Data belum terisi"<<endl;
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 4:
{
ig *show;
show=tail;
while(show!= NULL)
{
cout<<tail->id<<endl;
cout<<tail->name<<endl;
tail=tail->next;
}
}
cout<<"your choices (1/2/3/4/5)";cin>>choose;
case 5:
{
return 0;
}
}
}
I tried to learn the logic of statement and the solution many times, but still unsuccessful. So I need help here, thank you
Put a while around the switch:
while (true) {
int choose = askChoice();
switch (choose)
{
case 1: AddInstagramID(); break;
case 2: LookAllData(); break;
case 3: LookPreviousData(); break;
case 4: LookNextData(); break;
case 5: return 0;
}
}

Sorting array of pointers

I am trying to sort an array of pointers, which are pointing to a character array of names. I can get the program to sort the first two names but not the rest. Also the names are part of a structure.
void sort( Class* ptrs[], int num_classes){
bool swap=false;
do
{
swap=false;
for (int i=0; i<=num_classes-1; i++) {
if (ptrs[i]->title[i]>ptrs[i+1]->title[i]) {
Swap(&ptrs[i], &ptrs[i+1]);
swap=true;
}
}
}while(swap);
}
void Swap(Class** num1,Class** num2){
Class* temp=*num1;
*num1=*num2;
*num2=temp;
}
struct Class{
char title[MAX];
int units;
char grade;
};
int main(){
int choice,num_classes=0;
char class_selection[MAX];
Class* ptrs[MAX];
char* class_ptr[MAX];
bool Continue=false;
Class classes[MAX];
for (int i = 0; i < MAX; i++){
ptrs[i]=&classes[i];
}
cout<<" 1. Add new class"<<endl<<" 2. Edit an existing class"<<endl<<" 3. Display a class"<<endl<<" 4. List all classes"<<endl<<" 5. Display GPA"<<endl<<" 6. Delete all classes"<<endl<<" 7. Quit"<<endl<<"Enter selection number: ";
cin>>choice;
if (choice!=7) {
Continue=true;
}
switch (choice) {
case 1:
add(ptrs,num_classes);
num_classes++;
break;
case 2:
edit(ptrs,num_classes);
cin.ignore();
break;
case 3:
sort(ptrs,num_classes);
cin.ignore();
cout<<"Enter the name of the class to display: ";
cin.getline(class_selection, MAX);
for (int j =0; j<MAX; j++) {
class_ptr[j]=&class_selection[j];
}
Bin_search(ptrs,num_classes,class_ptr);
break;
case 4:
sort(ptrs,num_classes);
display(ptrs,num_classes);
break;
case 5:
// display_GPA();
break;
case 6:
// delete_end();
break;
}
if (choice == 7) {
// delete_end();
//system('pause");
return 0;
}
}
This code is comparing i-th character of corresponding titles, not the whole titles:
if (ptrs[i]->title[i]>ptrs[i+1]->title[i]) {
// ^^^ ^^^
Possible ways to solve:
Change this
char title[MAX];
to
std::string title;
And after that you'll be able to write
if (ptrs[i]->title > ptrs[i+1]->title) {
Only if you can't use std::string for some reason, use strcmp:
if (strcmp(ptrs[i]->title, ptrs[i+1]->title) > 0) {

menue driven program to perform the following queue operation using array en-queue, de-queue, count the number of elements and display in c++?

i need to make a C++ program for
menu driven program to perform the following queue operation using array en-queue, de-queue, count the number of elements and display in c++?
how to make this one ?
im very weak in c++ can anyone guide me or help me or link me to a complete program to study it and understand it?!!!
i tried but i coudnt do it so i really need help
is this right or not ?
#include<iostream.h>
#include<conio.h>
void push(int st[],int data,int &top); //declaring a push class
void disp(int st[],int &top); //declaring display class
int pop(int st[],int &top); //declaring a pop class
int flg=0;
int top=-1,tos=-1;
int st[50];
void push(int st[],int data,int &top) //push
{
if(top==50-1)
flg=0;
else
{
flg=1;
top++;
st[top]=data;
}
}
int pop(int st[],int &top) //pop
{
int pe;
if(top==-1)
{
pe=0;
flg=0;
}
else
{
flg=1;
pe=st[top];
top--;
}
return(pe);
}
void disp(int st[],int &top) //display
{
int i;
if(top==-1)
{
cout<<"\nStack is Empty";
}
else
{
for(i=top;i>=0;i--)
cout<<"\t"<<st[i];
}
}
void main()
{
int dt,opt; // declare varible
int q=0;
clrscr();
cout<<"\t\t\tStack operations";
cout<<"\n\n\tMain Menu.........";
cout<<"\n\n1.Push";
cout<<"\n\n2.Pop";
cout<<"\n\n3.Exit";
cout<<"\n\n4.display";
do // useing do while for to make choice and select any options
{
cout<<"\n\n\tEnter Your Choice 1-4:"; //entering your choice
cin>>opt;
switch(opt)
{
case 1:
cout<<"\nEnter the Element to be Push:";
cin>>dt;
push(st,dt,tos);
if(flg==1)
{
cout<<"the push is done";
if(tos==50-1)
cout<<"\nStack is Now Full";
}
else
cout<<"\nStack Overflow Insertion Not Possible";
break;
case 2:
dt=pop(st,tos);
if(flg==1)
{
cout<<"\n\tData Deleted From the Stack is:"<<dt;
cout<<"\n \t pop is done";
}
else
cout<<"\nStack Empty,Deletio Not Possible:";
break;
case 3:
q=1;
break;
default:
cout<<"\nWrong Choice Enter 1-3 Only";
case 4:
disp(st,tos);
break;
}
} while(q!=1);
}
There is a queue collection in the STL library which provides all of the functionality required above for you, if for some reason you are not allowed to use this then I suggest the following logic might be helpful
when an item is popped from the front of the queue all other items must be copied down 1 element, use a for loop for this
E.g
for (int index = 1; index < arraySize; index++)
{
if (item[index] == -1)
{
item[index-1] = -1;
break;
}
item[index - 1] = item[index];
}
when an element is deleted, all items that follow that item in the queue must be moved down 1 space, find the index of the element being deleted and use a for loop
E.g
for (int index = deletedItemIndex; index < arraySize; index++)
{
if (item[index] == -1)
break;
item[index] = item[index + 1];
}
when an item is added to the queue it is simply placed at the end of the queue, but not necessarily the end of the array (perhaps initialise all the array elements with -1 to start, that way you can easily test if you are at the end of the queue)

Stack-based palindrome checker

i have a problem with my program. It should be program that recognize palindome through the stack. Everything works great, only thing that don't work is printing stacks(original and reversed) after the funcion is done.
Here is my entire code, and the problem is at case d and e:
#include <iostream>
using namespace std;
const int MAXSTACK = 21;
class stack {
private:
int stop;
char stk[MAXSTACK];
public:
stack();
~stack();
stack(const stack& s);
void push(const char c);
char pop();
char top(void);
int emptystack(void);
int fullstack(void);
void stack_print(void);
int stack::create(void);
};
stack::stack()
{
stop = 0;
}
stack::~stack() { }
stack::stack(const stack& s)
{
stop = s.stop;
strcpy(stk,s.stk);
}
void stack::push(const char c)
{
stk[stop++] = c;
}
char stack::pop()
{
return stop--;
}
char stack::top(void)
{
return stk[stop - 1];
}
int stack::emptystack(void)
{
return !stop;
}
int stack::fullstack(void)
{
return stop == MAXSTACK;
}
void stack::stack_print(void)
{
for (int i=0; i<stop; i++)
cout<<stk[i];
cout<<endl;
}
int stack::create(void)
{
return !stop;
}
char menu()
{
char volba;
cout<<"\n";
cout<<" **********.\n";
cout<<"\n";
cout<<" a ... make new containers\n";
cout<<" b ... delete content\n";
cout<<" c ... enter string\n";
cout<<" d ... print on screen first stack\n";
cout<<" e ... print on screen first stack\n";
cout<<" f ... is it palindrom\n";
cout<<" x ... exit\n";
cout<<"\n your choice : ";
cin >> volba;
return volba;
}
int main() {
char palindrome[MAXSTACK];
char volba;
stack original,reversed;
int stackitems = 0,i;
//cin.getline(palindrome,MAXSTACK);
do{
volba = menu();
switch (volba)
{
case'a':
{
original.create();
reversed.create();
cout<<"done'";
break;
}
case'b':
{
original.emptystack();
reversed.emptystack();
cout<<"empty";
break;
}
case'c':
{
cout<<"enter your string"<<endl;
cin.get();
//cin.get();
cin.getline(palindrome,MAXSTACK);
for(int o = 0; o < strlen(palindrome); o++)
if (isalpha(palindrome[o]))
{
original.push(tolower(palindrome[o]));
stackitems++;
}
original.stack_print();
break;
}
case'd':
{
original.~stack();
for(int g = 0; g < strlen(palindrome); g++)
original.push(tolower(palindrome[g]));
original.stack_print();
}
/*//cin.getline(palindrome,MAXSTACK);
for(int g = 0; g < strlen(palindrome); g++)
if (isalpha(palindrome[g]))
{
original.push(tolower(palindrome[g]));
stackitems++;
}
}
original.stack_print();*/
break;
/*{
cout<<"original: ";
original.stack_print();
break;
}*/
break;
case'e':
{
cout<<"reversed:"<<endl;
for( i = 0; i < stackitems; i++) {
reversed.push(original.top());
original.pop();
}
reversed.stack_print();
}
break;
case'f':
{
for( i = 0; i < stackitems / 2; i++) {
reversed.push(original.top());
original.pop();
}
if (stackitems % 2)
original.pop();
while (!original.emptystack()) {
if (original.top() != reversed.top()) break;
original.pop(); reversed.pop();
}
if (original.emptystack())
cout << "it is palindrom\n";
else
cout << "not palindrom\n";
break;
}
default:cout<<"!??!";
}
} while(volba!='x');
}
You've explicitly called your stack's destructor. There is almost never a good reason to do this. If the stack is a local ("on the stack", hee hee), the compile will do it for you. If it's on the heap, created with new, call delete on it, which will cause the compiler to call the destructor.
case'd':
{
original.~stack();
You have commented palindrome reading :)
//cin.getline(palindrome,MAXSTACK);
There are a few things I would like to respond with. First, I think GMan, tpdi, and Vinay all have good points. This FAQ explains why calling the destructor on a local variable is a bad idea.
I realize this is just a simple homework problem and you are probably just trying to keep your stack class lightweight, but you might consider using a container class instead of an array of characters in your stack class.
Next, I'm not sure your emptystack and create functions are doing what you think they are doing. When you declare your original and reversed stack classes in the main program the memory is allocated for your internal character array. It's not really necessary in this case to have a create function. Perhaps if you were allocating memory on the heap for your character array, you would put that code into the create function (if you chose to leave it out of the constructor for some reason), but that's not the case here.
Similarly, emptystack isn't really doing anything. It would be better to have empty stack set the stop member variable to 0. At least that way the stack would appear to be empty the next time someone tried to use it.
There's a lot more that could be said about this class, but it might be better if you tried some of the suggestions here like using the std::stack and debugging. This is, after all, your homework assignment: it will help you a lot more in the future if you find the solution yourself!