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?
Related
So recently i started to getting into stacks ADT in c++ and i am trying to create a small program which the user inserts a string and the output should be in reverse order
But something is going wrong with my code or i am missing something but i cant figure it out
My output so far is that i can insert the string but then it just output the couts "Reverse string" and nothing else
i tried several ways like to change the pop function but nothing changed
Thank you for any help
#include <iostream>
#include <string>
using namespace std;
class ReverseString {
public:
string str[13];
int topStack;
ReverseString() {
topStack = -1;
}
string Push() {
//char item;
string str("");
cout << "Enter a string " << endl;
cin >> str;
for (char ch : str) {
topStack++;
// str[topStack] = item;
return str;
}
}
string Pop() {
string temp= str[topStack];
for (int i = 0; i <= 13; i++) {
str[i] = temp;
//temp = str[i - 1];
cout << "Reverse String: " << str[topStack] << endl;
return temp;
}
}
};
// main function
int main() {
ReverseString str;
str.Push();
str.Pop();
return 0;
}
At the beginning I apologize for my English.
I was trying to write a XML Parser that I encountered a weird problem.
to explain my problem I should say, I have a xml parser class that has an ifstream member. And this class has a function which reads until it reaches an open tag matching with the given input.
this is the parser class I was working on:
// XMLParser.cpp
#include <fstream>
#include "Stack.h"
using namespace std;
class XMLParser{
private:
int charReadRate = 3;
public:
ifstream *stream;
XMLParser(string add){
stream = new ifstream(add); // open input stream
}
void nextTag(string tag){
// find the first occurance of open-tag with name 'tag'
cout << "nextTag\n";
char * readData;
string tagName="";
stream->read(readData, charReadRate);
int len = string(readData).length();
int i = 0;
// cout << len << endl;
while(true){
if((*readData) == '<'){
readData++;
i++;
while(*readData != '>'){
tagName+=*readData;
readData++;
i++;
if(i>=len){
if(stream->eof()){
return ; // error didn't find
}
stream->read(readData, charReadRate);
// cout << readData << endl;
len = string(readData).length();
i = 0;
}else{
if(tagName == tag){
// cout << "find\n";
stream->seekg(i-len, ios::cur);
return;
}
}
}
}else{
readData++;
i++;
if(i>=len){
if(stream->eof()){
return ; // error didn't find
}
stream->read(readData, charReadRate);
len = string(readData).length();
i = 0;
}
}
}
}
};
in the nextTag function I read the file until I reach the open tag which name's matches with the given input.
and here is my main function
int main(){
XMLParser parser("test.xml");
cout << "ready\n";
parser.nextTag("Log");
char *c;
parser.stream->read(c,3);
cout << c << endl;
return 0;
}
I have figured out that the program crashes when the fifth line of the main function [parser.stream->read(c,3);] is executed.
I wonder why this happens?
The char pointer you pass to ifstream::read is not initialized and thus points to an invalid memory region, causing your program to crash. You need it to point to a buffer you allocated:
int main(){
XMLParser parser("test.xml");
cout << "ready\n";
parser.nextTag("Log");
char c[3];
parser.stream->read(c,3);
cout << c << endl;
return 0;
}
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;
}
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.
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.