C++ string size changing during loop - c++

My Program is suppose to read a string and then insert each character into the stack. I noticed when I print the length, which is the size of the word, it changes to some high number. For example: word = "hello" length will = 5 at first but eventually change to = 111. Also When I use 2 letters I always get a segmentation fault. What is causing this? Why is the length of the word changing?
#include <iostream>
#include <string>
#include "Stack.h"
using namespace std;
int main()
{
Stack stack;
string word;
cout << "Enter word: ";
getline(cin, word);
cout << word << "|" << endl;
int length = word.size();
for (int i = 0; i < length; i++) {
cout << "i: " << i << "\tlength: " << length << endl;
stack.push(word[i]);
cout << "TOP: " << stack.top() << endl;
}
while (!stack.isEmpty())
{
cout << stack.pop();
}
cout << endl;
return 0;
}
#include <iostream>
#include <string>
#define STACK_CAPACITY 1000
using namespace std;
class Stack
{
private:
int topIndex;
char arr[];
public:
// Constructor
Stack()
{
arr[STACK_CAPACITY];
topIndex = -1;
}
// adds elements to "top" of array
void push(char c)
{
// if stack is full, do not add
if (isFull())
{
cout << "Push on full Stack" << endl;
// terminate function
}
topIndex++;
arr[topIndex] = c;
}
// Removes last inserted (push) element from the stack and returns it
char pop()
{
// checks if Stack is empty
if (isEmpty())
{
cout << "Pop on empty Stack" << endl;
return '#';
}
// if not empty, remove and return last element inserted
char temp = arr[topIndex];
arr[topIndex--] = ' ';
return temp;
}
// Returns but does not remove last inserted (push) element
char top() { return arr[topIndex]; }
// Utilities
bool isEmpty() { return topIndex == -1; }
bool isFull() { return topIndex == STACK_CAPACITY - 1; }
int size() { return topIndex + 1; }
// Destructor
~Stack()
{
}
}

There are various problems in your Stack class that cause it to exhibit undefined behaviour.
For example, in the constructor
Stack()
{
arr[STACK_CAPACITY];
topIndex = -1;
}
does not (as, I guess, you are expecting) resize arr to have STACK_CAPACITY elements. It attempts to evaluate the value of arr[STACK_CAPACITY] which, since arr is declared as char arr[], does not exist. Hence that statement has undefined behaviour.
Similarly, the push() member function
// adds elements to "top" of array
void push(char c)
{
// if stack is full, do not add
if (isFull())
{
cout << "Push on full Stack" << endl;
// terminate function
}
topIndex++;
arr[topIndex] = c;
}
attempts (on the first call) to modify arr[0] - which also does not exist.
When behaviour is undefined - as it is in the above - anything can happen. Including appearing to overwrite unrelated data or (in your case) overwriting parts of the string word in main().
You need to read up better on the basics of C++, rather than guessing about how things work. You have guessed VERY incorrectly.

Related

how to push and pop elements read from a textfile to an array in c++ and output the stack in revserse order?

Hi I am new to c++ and am having trouble understanding on how I would push and pop elements read from a text file to an array and displaying those elements in reverse order for example if i have a text file called hero.txt with elements Goku Luffy Naruto I would like the output to be Naruto Luffy Goku
this is what I have so far
string hero[100]; // array to store elements
int count=0;
int main()
{
fstream myfile;
string nameOffile;
string text;
string mytext;
cout << "Enter name of file" << endl;
cin >> nameOffile
myfile.open(nameOffile.c_str());
if (!myfile)
{
cerr << "error abort" << endl;
exit(1);
}
while (myfile >> text )
{
Push(mytext); //Note I know this is wrong I just don't know how to write it in a manner that will push the first element of the textfile to the top
}
myfile.close();
while(hero[count]=="")
{
//Again I know these two lines are incorrect just don't know how to implement in correct manner
cout <<hero[0] << " " <<endl;
Pop(mytext);
}
}
// Function for push
void Push(string mytext)
{
count = count + 1;
hero[count] = mytext;
}
void Pop(string mytext)
{
if(count=0)
{
mytext = " ";
}
else
{
mytext = hero[count];
count = count - 1;
}
}
Normally, a stack will begin with index = -1 to indicate that the stack is empty. So you need to replace
int count = 0
with
int count = -1
After you do all the pushing, your stack will look like this:
hero[0] = "Goku"
hero[1] = "Luffy"
hero[2] = "Naruto"
Now, to print it out in reverse order, you can just loop from the last index to the first. After pushing all the heroes string, count is now equal to 2. The last heroes will be at index = 0. So you can rewrite the loop as
while(count >= 0)
{
cout << hero[count] << " " <<endl;
Pop();
}
Your Pop function is also incorrect. In the if statement, you will replace the value of count to 0. What you need to do in Pop is just to decrement the value of count.
So you can rewrite it as
void Pop()
{
count = count - 1;
}
The vector class defined in the standard library acts like a stack.
For example:
// include the library headers
#include <vector>
#include <string>
#include <iostream>
// use the namespace to make the code less verbose
using namespace std;
int main()
{
// declare the stack
vector<string> heroStack;
// insert the elements
heroStack.push_back("Goku");
heroStack.push_back("Luffy");
heroStack.push_back("Naruto");
// print elements in reverse order
while(!heroStack.empty())
{
// get the top of the stack
string hero = heroStack.back();
// remove the top of the stack
heroStack.pop_back();
cout << hero << endl;
}
}
ok let's tart by improving your functions
push function works good but just change the order of it to be like this
void Push(string mytext)
{
hero[count] = mytext; //now you will start at index 0
count = count + 1;
}
pop function should be like this
you need to return a string value and you don't need to pass a parameter
string Pop()
{
if(count == 0)
{
return "";
}
else
{
count = count - 1;
mytext = hero[count];
return mytext;
}
}
now you are functions are ready let's use them
you are using the push function correctly in your main
we need to change the while which displays the output
it should be like this
while(true)
{
tempText = pop(); // this function will get you the last element and then remove it
if ( tempText == "" ) // now we are on top of the stack
break;
cout <<tempText << " " <<endl;
}
#include "stdafx.h"
#include <fstream>
#include <stack>
#include <string>
#include <iostream>
class ReadAndReversePrint
{
std::stack<std::string> st;
std::ifstream file;
public:
ReadAndReversePrint(std::string path)
{
file.open(path);
if (file.fail())
{
std::cout << "File Open Failed" << std::endl;
return;
}
std::string line;
while (!file.eof())
{
file >> line;
st.push(line);
}
file.close();
std::cout << "Reverse printing : " << std::endl;
while (!st.empty())
{
std::cout << st.top().c_str() << "\t";
st.pop();
}
std::cout << std::endl;
}
};
int main()
{
ReadAndReversePrint rrp("C:\\awesomeWorks\\input\\reverseprint.txt");
return 0;
}

Heap Corruption at class destructor?

I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong.
I wrote a c++ code with class implementing a simple stack, trying to push and pop random stream of characters. It seems to work fine, but at the end of the file, it produces some sort of runtime error:
HEAP CORRUPTION DETECTED: after Normal block....
Since the error occurs at the end of the file, my guess is that there is a problem at deleting the pointer(class destructor). However, I have no idea what is wrong with the destructor I wrote.
Also, after some trial and error, I found out that if I address a bigger number to unsigned integer value iter1 (ex: 80), the runtime error does not occur. Could you explain what is the problem here, and how to bypass it?
stack.h:
class sstack
{
public:
sstack(int length = 256);
~sstack(void);
int sstackPop(char &c);
int sstackPush(char c);
bool isempty();
bool isFull();
protected:
private:
char *sstackBuffer;
int sstackSize;
int sstackIndex; // Initial = -1
};
stack.cpp:
#include "stack.h"
#include <iostream>
using namespace std;
sstack::sstack(int length)
{
sstackIndex = -1;
if (length > 0)
sstackSize = length;
else
sstackSize = 256;
sstackBuffer = new char[sstackSize];
}
sstack::~sstack(void)
{
delete[] sstackBuffer;
}
bool sstack::isempty()
{
if (sstackIndex < 0)
{
cout << "is empty!(isempty)" << endl;
return 1;
}
else
return 0;
}
bool sstack::isFull()
{
if (sstackIndex >= sstackSize)
return 1;
else
return 0;
}
int sstack::sstackPop(char &c)
{
if (!isempty())
{
c = sstackBuffer[sstackIndex--];
cout << sstackIndex << endl;
return 1;
}
else
{
cout << "is empty!(sstackPop)" << endl;
return 0;
}
}
int sstack::sstackPush(char c)
{
if (!isFull())
{
sstackBuffer[++sstackIndex] = c;
return 1;
}
else{
return 0;
}
}
main.cpp:
#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
int main(){
unsigned int iter1 = 5;
unsigned int iter2 = 800;
sstack stackDefault;
sstack stack1(iter1);
sstack stack2(iter2);
char buffer[80];
memset(buffer, 0x00, 80);
char BUFFER[80] = "A random stream of characters";
strcpy_s(buffer, 80, BUFFER);
for (int i = 0; i< strlen(buffer); i++)
{
cout << " stack1: " << stack1.sstackPush(buffer[i]);
cout << " stack2: " << stack2.sstackPush(buffer[i]);
cout << " stackD: " << stackDefault.sstackPush(buffer[i]);
cout << " i : "<< i << endl;
}
cout << "out of Pushes" << endl;
int i = 0;
memset(buffer, 0x00, 80);
while (!stack1.isempty())
stack1.sstackPop(buffer[i++]);
cout << buffer << endl;
getchar();
}
sstackBuffer[++sstackIndex] = c;
Will write past the end of sstackBuffer when the stack only has one element left.
If you consider a stack of size 1. In the first call to push that line would evaluate to:
sstackBuffer[1] = c;
Which is beyond the memory you've allocated.
Be sure you're aware of the difference between pre-increment and post-increment operators. By your code example I would suggest you use post-increment in push and pre-increment in pop.

Compilier not Entering Functions Properly

I am trying to write a program that calls a custom function. Unfortunately, once it enters the function, it ceases to print what I told it to and gets stuck indefinitely. (I run a mac 10.9, and the newest Xcode)
The two functions are:
int main(void)
{
string filePath;
treeNode* root;
int words;
//filePath = getFileName();
cout << "Choosing pathway.\n";
root = readIn(words, "/Users/Noah/Desktop/SmallFile.txt");
cout << "File read.\n";
root->printInOrder(root);
}
and:
treeNode* readIn (int& count, string file)
{
cout << "Here. ";
treeNode* root = new treeNode;
string insert;
ifstream reading;
count = 0; // DECLARE VARIABLES!
int size = 0;
cout << "Made variables. ";
reading.open(file); // Open and check file
cout << "File up. ";
//for (int i = 0; i < 15; i++) // See coder's note at top.
while (!reading.eof())
{
cout << "In loop. ";
char c = reading.get(); // Obtain character to check
if (isalnum(c))
{
insert += c; // Word Storage update
}
else
{
if (count != 0)
{
insertWord(insert, root); // Insert word
insert.clear();
size = 0;
count ++;
}
}
}
reading.close();
return root; // Gives top node back.
}
My question is: Are there any obvious errors that would cause this? If not, is it compiler related? And is there anything I can do about it?

No output when merge function is called

I have a doubt in the following code. Can somebody please explain.
using namespace std;
#define INT_SIZE 32
#define R 4
#define C 4
#define N 4
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<limits.h>
#include<stack>
#include<vector>
#include<algorithm>
struct interval{
int start;
int end;
};
bool compareInterval(interval i1, interval i2)
{
return (i1.start < i2.start)? true: false;
}
int merge(vector<interval>& a, int n)
{
stack<interval> s;
sort(a.begin(), a.end(), compareInterval);
s.push(a[0]);
int i=1;
interval temp;
while(i<n)
{
temp = s.top();
s.pop();
if(temp.end > a[i].start && a[i].end > temp.end)
{
temp.end = a[i].end;
s.push(temp);
}
else if(temp.end < a[i].start)
{
s.push(temp);
s.push(a[i]);
}
i++;
}
while(s.size())
{
temp = s.top();
cout << temp.start << " ";
cout << temp.end << "\n";
s.pop();
}
return 0;
}
int main()
{
interval intvls[] = { {6,8}, {1,9}, {2,4}, {4,7} };
vector<interval> intervals(intvls, intvls+4);
for(int i=0;i<4;i++)
{cout << intervals[i].start;
} // This output is not coming when merge function is called
cout << merge(intervals, 4);
}
My doubt is "When I comment the merge function call i.e
// cout << merge(intervals, 4);
When I comment this line, then I am able to see output of cout<<intervals[i].start.
Otherwise, I am not able to see the output.
"
You are not ending your output with a newline. Try:
{cout << intervals[i].start << "\n";}
Without the newline, this output is probably getting hidden amongst all the output produced by merge().
There are few issues with this code.
s.push(a[0]); <-- Only on element is in you stack.
//s.push(a[1]).. you will have to add all other elements like this.
while(i<n)
{
temp = s.top(); <-- for second i s will be empty. Here you must check if stack is empty before getting top element.
s.pop();
}
Your first output is not printed correctly. use std::endl
cout << intervals[i].start << endl;
There is a bug in merge that leads to a segmentation fault. Due to this std::cout is not flushed. If you comment out the line with the merge call, std::cout is flushed when the program exits.

How can I modifiy my c++ program to show a word inputted by a user, backwards using a stack?

I want to assign a pointer to every character the user inputs. Then in doing so, I probably can use a loop to store the characters and a second loop rearrange the stack order using the pointers. But I don't know how to write that in a program form, and I'm not sure if it can work. Here is what I have so far:
#include<iostream>
using namespace std;
class Stack{
public:
enum {MaxStack = 50};
void init() {top = -1;}
void push( char n ){
if ( isFull() ) {
cerr << "Full Stack. DON'T PUSH\n";
return;
}
else {
arr[ ++top ] = n;
cout << "Just pushed " << n << endl;
return;}
}
int pop() {
if (isEmpty() ) {
cerr << "\tEmpty Stack. Don't Pop\n\n";
return 1;
}
else
return arr[top--];
}
bool isEmpty() {return top < 0 ? 1 : 0;}
bool isFull() {return top >= MaxStack -1 ? top : 0;}
void dump_stack() {
cout << "The Stack contents, from top to bottom, from a stack dump are: " << endl;
for (int i = top; i >= 0; i--)
cout << "\t\t" << arr[i] << endl;
}
private:
int top;
int arr[MaxStack];
};
int main()
{
Stack a_stack;
int x = 0;
char inputchar;
cout<<"Please enter a word"<<endl;
a_stack.init();
while (inputchar != '.') //terminating char
{
cin >> inputchar;
array[x] = inputchar;
x++;
}
int j = x;
for (int i = 0; i < j; i++)
{
cout << array[x];
x--;
}
a_stack.push();
a_stack.dump_stack();
return 0;
}
A stack, by its very LIFO nature (Last In, First Out), will reverse the order of anything you put in it. Example for string "Hello":
(The top of the stack is to the left)
H push "H"
eH push "e"
leH push "l"
lleH push "l"
olleH push "o"
Now when you pop from the stack, you'll first get "o", then "l", etc. It's whatever you put in but in reverse order. You don't need to do anything special to achive that. Just push to stack in normal order, and when you pop you'll get it reversed:
// while loop
{
cin >> inputchar;
a_stack.push(inputchar);
}
// Display in reverse
while (not a_stack.isEmpty()) {
cout << (char)a_stack.pop();
}
Here's a small example program using std::stack:
(No input error checking is done here.)
#include <iostream>
#include <stack>
int main()
{
std::stack<char> st;
char c = '\0';
while (c != '.') {
c = std::cin.get();
st.push(c);
}
while (not st.empty()) {
std::cout << st.top();
st.pop();
}
std::cout << '\n';
}
Example input and output:
Hello world.
.dlrow olleH
Unless using a stack is a must (i.e. it is a homework), you might be better off with getline(), its parameter delim (cf getline) followed by a reverse loop over the array. It would be faster, cleaner, less prone to errors and basically a two-liner.