Why won't the string push or pop in stack [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
This is an assignment given to me.
I am a noob just started programming.
The string as a whole won't push onto the stack and how to pop it.
Problem statement:- divide a whole string consisting of a full name, divide the string into 3 parts to get the first name middle name and surname and display them in the order of surname first name middle name USING STACKS ONLY.
I've tried using 2D stack
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string>
using namespace std;
using std :: string;
char s1[100];
char s2[50],s3[50],s4[50];
int i=0,j=0,k=0,max1=9,top=-1;
char stack[10][10];
char re[10];
void push(char val[])
{
if(top>=max1)
{
cout<<"Stack overflow";
}
else
{
top++;
int a=0;
for (int i=0;i<stack[top]['\0'];i++)
{
stack[top][a]=val[i];
a++;
}
}
}
char* pop()
{
if(top<0)
{
cout<<"Stack underflow";
}
else
{
//for(int j=0;j<=top)
for(int i=0;i<stack[top]['\0'];i++)
{
re[i]=stack[top][i];
top--;
return re;
}
}
}
void divstring()
{
for(i=0;s1[i]!=' ';i++)
{
s2[i]=s1[i];
}
s2[i]='\0';
i++;
while(s1[i]!=' ')
{
s3[j]=s1[i];
j++;
i++;
}
s3[j]='\0';
i++;
while(s1[i]!='\0')
{
s4[k]=s1[i];
k++;
i++;
}
s4[k]='\0';
i++;
}
int main()
{
//clrscr();
cout<<"Enter the string: ";
gets(s1);
divstring();
cout<<"The 1 part is "<<s2<<endl;
cout<<"The 2 part is "<<s3<<endl;
cout<<"The 3 part is "<<s4<<endl;
// getch();
push(s1);
push(s2);
push(s3);
cout<<pop();
return 1;
}
There are no compile time errors but the strings don't get pushed onto the stack nor popped.

There's multiple problems here.
There is no such thing as a 2D stack. A stack is one dimensional. It's got one usable end. In C++, you use std::stack, push(), pop() and empty().
You need to get rid of the global variables.
You seem to want to implement your own stack. You need to decide, do you want to implement a stack, that is one question. Or, do you want to use an existing stack to perform the assignment? that's a different question. I can't tell between the two.
You should use std::string.
You don't handle boundary condition. For example passing a string without spaces will loop infinitely in
for(i=0;s1[i]!=' ';i++)

The push function is very confused, here's a working version
void push(char val[])
{
if (top >= max1)
{
cout << "Stack overflow";
}
else
{
top++;
int i = 0;
for (; val[i] != '\0'; i++)
stack[top][i] = val[i];
stack[top][i] = '\0';
}
}
There are many ways you could improve this, you could use the C strcpy function instead of copying your strings by hand. Or, heaven forbid, you could use some C++, like std::string and std::stack.

Related

I can not do a swap operation while sorting. It crashes when I do it. Why? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
struct Dates
{
int day;
int month;
int year;
}accountinfo[3];
struct Accounts
{
string name,lastname;
int number;
float balance;
}account[3];
void sortduetoaccnumbers()
{
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
if (account[j].number>account[j+1].number)
{
//swap
}
}
}
}
void sortduetodates()
{
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
if (accountinfo[j].year>accountinfo[j+1].year)
{
//swap
}
else if (accountinfo[j].year==accountinfo[j+1].year)
{
if (accountinfo[j].month>accountinfo[j+1].month)
{
//swap
}
else if (accountinfo[j].month==accountinfo[j+1].month)
{
if (accountinfo[j].day>accountinfo[j+1].day)
{
//swap
}
}
}
}
}
}
I can not sort these accounts using sorting algorithms. It crashes if I enter them. cmd stops suddenly and finishes the program.
I entered a comment line where swapping functions have to go. So you can analyze the code.
Every other functions are working except this one. I'm stuck at this point.
this code is wrong:
if (accountinfo[j].year>accountinfo[j+1].year)
because if j==2, then j+1=3 - index over array size => undefined behavior (and crash in your case)
you need to change loop condition to j<2 or rewrite your checks

C++, return array from function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Im building this subnet calculator but now im stuck, with array. I want to create new int function that will return array, but I don't know how I tried many things but still don't have idea, think it will have to do something with pointers. I want to create new function starting at "while(octet4>0)". so octet4 gets passed into function and function should return fully functional array which I can use then in main. Hope somebody will know answer for what im looking for, hope solution would not be too complicated because Im just learning programming and thought this would be fun project to take on.
int main() {
int i=0,j,q,s,size=8,temp;
int binary_ip[8];
int netmask;
int mask;
int octet1, octet2, octet3, octet4;
string ip;
cout<<"Vnesite IP naslov, npr. 192.168.32.55:"<<endl;
cin>>ip;
cout<<"Vnesite netmasko, npr. /27:"<<endl;
cin>>netmask;
stringstream stream(ip);
char ch;
stream >> octet1 >> ch >> octet2 >> ch >> octet3 >> ch >> octet4;
while(octet4>0){
binary_ip[i]=octet4%2;
i++;
octet4=octet4/2;
}
switch(i){
case 7:binary_ip[7]=0;
break;
case 6:for(s=6;s<=7;s++)binary_ip[s]=0;
break;
case 5:for(s=5;s<=7;s++)binary_ip[s]=0;
break;
case 4:for(s=4;s<=7;s++)binary_ip[s]=0;
break;
case 3:for(s=3;s<=7;s++)binary_ip[s]=0;
break;
case 2:for(s=2;s<=7;s++)binary_ip[s]=0;
break;
case 1:for(s=1;s<=7;s++)binary_ip[s]=0;
break;
}
for(q=0;q<size/2;q++){
temp=binary_ip[size-1-q];
binary_ip[size-1-q]=binary_ip[q];
binary_ip[q]=temp;}
return 0;
}
Some options:
Use std::array instead of a regular C array. Those are easier to work with and you are already using standard library. http://www.learncpp.com/cpp-tutorial/6-15-an-introduction-to-stdarray/
Have your function fill-in the array, rather than create and return it:
void MakeArray(int octet4, int binary_ip[8]) ;
Use pointers, allocate array with "new" and free it with "delete". You'll need a way to know the size of the array, however.
#include <iostream>
int array(int octet4, int binary_ip[]);
int main()
{
int binary_ip[6];
int octet4 = 55;
int i = 0;
i = array(octet4, binary_ip);//binary_ip passes in the address of the first element in the array
}
int array(int octet4, int binary_ip[])
{
int i = 0;
while(octet4>0)
{
binary_ip[i]=octet4%2;
i++;
octet4=octet4/2;
}
return i;
}
or you can use a vector like Daniel H suggested
void array(int octet4, std::vector<int> &binary_ip)
{
while(octet4>0)
{
binary_ip.push_back(octet4%2);
octet4=octet4/2;
}
}
int main()
{
std::vector<int> binary_ip;
int octet4 = 55;
array(octet4, binary_ip);
}

Postfix notation stack C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to C++ and I want to use a stack to evaluate an expression given as an input (2+3*5+4 for example), containing only numbers, + and *. I wrote this code but it gives me Segmentation fault: 11. Could you please help me solve this or give me a hint about what could be wrong? Thank you! (I noticed there were similar questions on this site, but I couldn't use them to solve my problem)
#include <iostream>
#include <stack>
using namespace std;
bool highPrecedence(char a, char b){
if((a=='+')&&(b=='*'))
return true;
return false;
}
int main()
{
char c = 'a';
double x;
stack<char> stack;
double v[10];
int i=0;
double res;
while(true)
{
c = cin.get();
if(c=='\n'){
while(stack.size()!=0){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
break;
}
if ( '0'<=c && c<='9' )
{
cin.putback(c);
cin>>x;
cout<<"Operand "<<x<<endl;
i=i+1;
v[i]=x;
}
else
{
if(c!=' ') cout<< "Operator " <<c<<endl;
if (stack.size()==0)
stack.push(c);
else{
while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
stack.push(c);
}
}
}
cout<<v[0]<<endl;
}
Using stack.top() is illegal if the stack is empty.
Change while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
to while((!stack.empty()) && (!highPrecedence(stack.top(),c))){
The initiali value of i is not good and you are printing uninitialized variable, which has indeterminate value.
Change int i=0; to int i=-1;

c++ Not able to add an element in the array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am fairly new to c++. I am trying to add another element in the array. The function should change the array and the number of items in the array after the addEntry function is completed, but it doesn't. If I use the display function to show the array, only the original array is shown. Please help.
#include<iostream>
#include<string>
using namespace std;
const int MAXSIZE = 10; // total size of array
void display(string[], int);
void addEntry(string[], int&);
int main()
{
string name[MAXSIZE] = {"raj","casey","tom","phil"};
int numEntries = 4; // number of elements in the array
string choice; // the user choice to add an element or display or exit
cout<<numEntries<<" names were read in."<<endl;
do
{
cout<<endl<<"Enter menu choice (display, add, quit): ";
getline(cin,choice);
if (choice == "display")
{
display(name, numEntries);
cout<<endl;
}
else if (choice == "add")
{
addEntry(name, numEntries);
cout<<endl;
}
else
{
cout<<"bye"<<endl;
}
} while (choice!="quit");
system ("pause");
return 0;
}
void display(string name[], int numEntries)
{
for (int i = 0; i < numEntries; i++)
{
cout<<name[i]<<endl;
}
return;
}
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE-1)
{
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
getline(cin,name[numEntries]);
numEntries is the number of valid entries in your array. name[numEntries] is the element that is following the last valid entry. Use name[numEntries-1].
Or even better, use std::vector instead of C arrays, after all, you are writing in C++.
Your program works, you are just pointing the the wrong location in your array in addEntry. Remember that arrays in C++ are 0-based, try incrementing the value of numEntries AFTER inserting the element in your array, for example:
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE)
{
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries++]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
The bug in your code is in the following lines:
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
You need to increment numEntries after the call to getline. Use:
cout<<"Enter name of the person to add: ";
if ( getline(cin,name[numEntries]) )
{
// Increment only if getline was successful.
numEntries++;
}

probmem with comparing string c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I just came from C to C++ and find difficulties with compare string method.
I have a simple task. I need to create a class of school Teachers, then make an object array, and after withdrow all Teachers, who's subject is similar to testSubject.
So here is my class
class Teacher
{
private:
string FamilyName;
string Name;
string Patronymic;
string sex;
int exp;
std::string subject;
string speciality;
int age;
public:
Teacher();
int getExp();
string getSubject();
int getAge();
void show();
};
And here is my func, that withdrow the list of Teachers, teaching the input subject
void ListTeacherSub (Teacher spis[], int n)
{
//List of teachers, who's subject is like testSubject
std::string testSubject;
cout<<"Enter test subject "; cin>>testSubject;
for (int i=0; i<n; i++)
{
if (spis[n].getSubject().compare(testSubject) == 0)
spis[i].show();
}
}
Here it is main() function
int main()
{
Teacher *spis;
int n;
cout<<"Enter numbers of student "; cin>>n;
spis = new Teacher[n];
for (int i=0; i<n; i++)
{
spis[i].show();
}
ListTeacherAge(spis, n);
ListTeacherEx(spis, n);
ListTeacherSub(spis, n);
delete[] spis;
return 0;
}
So, everything is working nice, but when program reaches ListTeacherSub(spis, n) it is stops working. I used to work with strcmp only, but it doesn't works with string, as I understood.
So I decided to look for different realizations, and found that one http://www.cplusplus.com/reference/string/string/compare/
How can i fix my problem?
This
if (spis[n].getSubject().compare(testSubject) == 0)
should be
if (spis[i].getSubject().compare(testSubject) == 0)
This is incorrect (and causes undefined behaviour as it going beyond the end of the array):
if (spis[n].getSubject().compare(testSubject) == 0)
as it using n and not the loop counter i.
Other:
always check the result of input operations to ensure variables have been correctly populated and subsequent code is not using uninitialised or stale values:
if (std::cin >> n)
{
spis = new Teacher[n];
}
prefer to avoid explicit dynamic memory management. In this case std::vector<Teacher> would be suitable:
if (std::cin >> n)
{
std::vector<Teacher> spis(n);
for (Teacher& t) t.show();
}
Pass spis by const Teacher& to functions to avoid copy (and the parameter n is now superfluous).
std::string instances can be compared using ==.