C++ program reports "Process terminated with status -1073741510" - c++

I am doing a algorithm and data structure exercise in C++ which requires to read a ten-word txt file then display them in a reserved order by using a stack without STL, class or struct. All the code looks good but it display nothing when I actually run it.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int mindex = -1;
string word[10];
void push(string p);
void top();
void pop();
bool isEmpty();
int main()
{
string filename,eli;
cout << "Please input a file name" << endl;
cin>>filename;
ifstream inData;
inData>>eli;
inData.open(filename);
if (!inData)
{
cerr<< "Error opening : " << filename << endl;
return -1;
};
while (inData >> eli)
{
if(inData.fail()){
break; }
else push(eli);
}
while (!isEmpty()){
top();
pop();
}
inData.close();
return 0;
}
void push(string p){
index++;
word[mindex] = p;
}
void pop(){
mindex--;
}
void top(){
cout<<word[mindex]<<" ";
}
bool isEmpty(){
return (mindex<0);
}

There are several mistakes and assumptions here that could go wrong. I will only focus on the immediately obvisous.
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // only for demos/slideware/toy projects.
int mindex = -1;
string word[10]; // we will only ever get 10 strings?
// 10 is a magic number use a const like const int maxWords = 10;
// using std::array will catch problems like this, std::vector can be used to dynamically resize the array.
void push(string p);
void top();
void pop();
bool isEmpty();
int main() {
string filename,eli;
cout << "Please input a file name" << endl;
cin>>filename;
ifstream inData;
inData>>eli; // reading from not open file!!!
inData.open(filename);
if (!inData) {
cerr<< "Error opening : " << filename << endl;
return -1;
};
while (inData >> eli) {
if(inData.fail()) {
break;
} else
push(eli);
}
while (!isEmpty()){
top();
pop();
}
inData.close();
return 0;
}
void push(string p){
index++; // did you mean mindex???
word[mindex] = p; // fatal error if mindex is not at least 0.
}
void pop(){
mindex--;
}
void top(){
cout<<word[mindex]<<" ";
}
bool isEmpty(){
return (mindex<0);
}
A check for mindex at/above 10 should be done somewhere unless you are absolutely sure there will never be more than 10 words.

Related

Trying to bubble sort data from file in an array, cant get it to sort. Just keeps displaying in its original order

I cant figure out what I'm doing wrong. I have tried everything I could think of, I have searched the internet for solutions, I just can not get it to work. Starting to lose my mind a bit.
I have another issue with in my second function with my file. Not sure why, but it's making me open the file within the function, even though I already opened the file in the first function.
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
//function prototypes
void openFile(ifstream &inFile);
void displayNumberAve(ifstream &inFile, int &count, int playerArray[], double averageArray[]);
void bubbleSort(int playerArray[], int count);
//global constant
const int SIZE = 50;
int main()
{
int playerArray[SIZE];
double averageArray[SIZE];
ifstream inFile;
int count;
//function call to open file
openFile(inFile);
// displayNumberAve(inFile, count, playerArray, averageArray);
// selectSort(playerArray, count);
bubbleSort(playerArray, count);
cout << "Sorted array below" << endl;
displayNumberAve(inFile, count, playerArray, averageArray);
return 0;
} // closes int main
/***********************************
//openFile
//function to open and test file
***********************************/
void openFile(ifstream &inFile)
{
inFile.open("battingInfo.txt");
if(!inFile)
{
cout << "File not found, dummy" << endl;
exit(1);
}//closes if
inFile.close();
} // closes function
/***********************************
//displayNumberAve
//displays array data in table
***********************************/
void displayNumberAve(ifstream &inFile, int &count, int playerArray[], double averageArray[])
{
inFile.open("battingInfo.txt"); //why is this refusing to show the file data unless i put this here?
cout << "Player Batting Average" << endl;
if(inFile.is_open())
{
while(!inFile.eof())
{
inFile >> playerArray[count];
inFile >> averageArray[count];
cout << setw(2) << left << playerArray[count] << right << setw(13) << averageArray[count] << endl;
}//closes while
}//closes if
}//closes function
/******************************************
//bubbleSort
//sort the plater array using bubble sort
******************************************/
void bubbleSort(int playerArray[], int count)
{
int maxElement;
int index;
int temp;
int count;
for (maxElement = count - 1; maxElement > 0; maxElement--)
{
for (index = 0; index < maxElement; index++)
{
if (playerArray[index] > playerArray[index + 1])
{
swap(playerArray[index] , playerArray[index + 1]);
}
}
}
}//closes void
Thanks in advance for any help
Your displayNumberAve should display the content of your playerArray.
Instead, it reads the content of the file "battingInfo.txt" into that array, and displays that.

Comparing stacks

I have a project to compare the contents of two stacks and I am having issues with this function. I believe I have the rest of the program done correctly. I am getting errors on B.myCharacters.empty() (Expression must have class type) and B==B.myCharacters (no operator "==" matched these operands).
bool CharStack::IsEqual(CharStack & B)
{
if (B.empty())
{
cout << "Stack is empty" << endl;
return false;
}
else if (B.myCharacters.empty())
{
cout << "Stack is empty" << endl;
return false;
}
else if (B == B.myCharacters)
return true;
}
Any help would be greatly appreciated.
Here is the header and driver. They were provided by the teacher for this project and I am not allowed to change them, even if there is a better way to do it.
#include <iostream>
#include <string>
using namespace std;
const int STACK_CAPACITY = 128;
typedef char StackElement;
class CharStack
{
private:
char myCharacters[STACK_CAPACITY]; // STL stack of chars.
int myTop;
public:
CharStack();
bool empty();
void push(const StackElement & value);
StackElement top() const;
void pop();
void StringToStack(const string & inStr);
friend ostream & operator <<(ostream & out, const CharStack & CS);
CharStack Reverse();
bool IsEqual(CharStack & B);
};
Driver
#include <string>
#include <cassert>
#include "Header.h"
using namespace std;
//introduces namespace std
int main(void)
{
ifstream in;
string fileName, line[30];
int i = 0;
CharStack N, M, P;
cout << "Enter file name for palindrome check: ";
cin >> fileName;
in.open(fileName.c_str());
assert(in.is_open());
while (!in.eof())
{
getline(in, line[i]);
N.StringToStack(line[i]);
cout << N << endl;
P = N;
M = N.Reverse();
if (P.IsEqual(M))
cout << "This line is a palindrome line" << endl;
else
cout << "This line is not a palindrome line" << endl;
i++;
}
cout << "\nProgram ended normally.\n";
system("pause");
}
Assuming your CharStack internally keeps the characters in a std::string, i.e.
class CharStack
{
std::string myCharacters; // internal data
public:
bool IsEqual(CharStack const&) const;
/* ... */
};
and IsEqual() should return if two stacks are identical, then the implementation is simply
bool CharStack::IsEqual(CharStack const&other) const
{
return myCharacters == other.myCharacters;
}
This compares an empty and a non-empty stack as not equal, but two empty stacks as equal, which arguably is the correct behaviour. If you want two empty stacks to be not equal you can
bool CharStack::IsEqualNonEmpty(CharStack const&other) const
{
return !myCharacters.empty() && myCharacters == other.myCharacters;
}
Note also the various uses of the keyword const.

Different results in Linux than in Windows C++

I've created my code in Microsoft Visual Studio Express 2013 and it compiles and runs fine. I've moved this over to Linux and it gives me a different result for the GPA output. The GPA's are coming as 0 and 6.95281e-310 instead of the 3.9 and 3.5.
Also wondering if there is a difference between the strcmp and strncpy in Linux since I had to add #include <cstring> in my student.h?
Is there something else I should be using instead of strncpy in Linux?
student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
public:
Student(const char initId[], double gpa);
bool isLessThanByID(const Student& aStudent) const;
bool isLessThanByGpa(const Student& aStudent) const;
void print()const;
private:
const static int MAX_CHAR = 100;
char id[MAX_CHAR];
double gpa;
};
#endif
student.cpp
#include "student.h"
//implement the required 3 functions here
Student::Student(const char initId[], double gpa) : gpa(gpa)
{
// initialize a newly created student object with the passed in value
strncpy(id, initId, Student::MAX_CHAR - 1);
if (Student::MAX_CHAR > 0)
{
id[Student::MAX_CHAR - 1] = '\0';
}
}
bool Student::isLessThanByID(const Student& aStudent) const
{
// compare the current student object with the passed in one by id.
if (strcmp(id, aStudent.id) > 0)
{
return true;
}
else
{
return false;
}
}
bool Student::isLessThanByGpa(const Student& aStudent) const
{
// compare the current student object with the passed in one by gpa
if (gpa < aStudent.gpa)
{
return true;
}
else
{
return false;
}
}
void Student::print() const
{
cout << id << '\t' << gpa << endl;
}
app.cpp
#include "student.h"
int main()
{
Student s1("G10", 3.9);
Student s2("G20", 3.5);
s1.print();
s2.print();
if(s1.isLessThanByID(s2))
{
cout << "about right!" << endl;
}
else
{
cout << "uhmm ..." << endl;
}
if(!s1.isLessThanByGpa(s2))
{
cout << "about right!" << endl;
}
else
{
cout << "uhmm ..." << endl;
}
//system("pause");
return 0;
}
strcmp compares strings http://www.cplusplus.com/reference/cstring/strcmp/
strncpy copies them http://www.cplusplus.com/reference/cstring/strncpy/
There IS a great diff really between them, in Linux and other systems as well.

How to use 'fout' with inheritance

I'm taking a class in C++ and I've run into a problem. We have to create a list of bankaccounts that each have their own savings and checking account. I've come quite far, but now I have to use "ofstream& fout" to print the checking and savings of an imaginairy account.
My header file of "Account.h" looks like this (I think it's correct):
#include <iostream>
#include <cmath>
#include <fstream>
#ifndef ACCOUNT_H
#define ACCOUNT_H
using namespace std;
class Account{
protected:
string number;
double balance;
public:
Account(){}
Account(string nr, double bl);
void deposit(double am);
string get_number();
double get_balance();
double withdraw(double am);
bool equals(Account other);
virtual void print();
void println();
void println(string s);
virtual void println(ofstream& fout);
virtual void read(ifstream& fin);
};
#endif
My definition file is where it all goes horribly wrong with the fstream part:
#include "Account.h"
Account::Account(string nr, double bl){
if (bl >= 0){
number = nr;
balance = bl;
}
else{
number = "incorrect";
}
}
void Account::deposit(double am){
if (am >= 0){
balance = balance + am;
}
}
string Account::get_number(){
return number;
}
double Account::get_balance(){
return balance;
}
double Account::withdraw(double am){
if (0 <= am && am <= get_balance()){
balance = balance - am;
return am;
}
else{
return 0;
}
}
bool Account::equals(Account other){
if (number == other.get_number()){
return true;
}
return false;
}
void Account::print(){
cout << "<Account(" << number << ",";
cout << balance << ")>" ;
}
void Account::println(){
print();
cout << endl;
}
void Account::println(string s){
cout << s;
println();
}
void Account::println(ofstream& fout){
fout << number << ",";
fout << balance;
fout << endl;
}
void Account::read(ifstream& fin){
fin >> number;
}
There is something wrong with the declaration of void Account::println(ofstream& fout). It gives me the output
<Account(number,balance,0)>
instead of
<Account(number,balance)>
Why does this happen? I have many more problems with the printing of the savings and checking numbers, but i feel if I understand why this is happening I can solve those. Thank you to anyone who wants to help me.
Account::println(ofstream&) will print "", but since the balance is a double, it prints with a decimal place:
if balance == 0.0, it will be printed as eiter 0.0 or 0,0, depending on your locale.
Either way, you have way too many print methods, and I think the solution should be implemented through an output operator:
Header:
class Account {
// ....
// no print methods defined
};
std::ostream& operator <<(std::ostream& out, const Account& a);
Source:
std::ostream& operator <<(std::ostream& out, const Account& a)
{
return out << "";
}
Client code:
#include <iostream> // console
#include <fstream> // file
Account a;
// print to console
std::cout << a << std::endl;
// print to file
std::ofstream fout("./account.txt");
fout << a << std::endl;

Binary Tree insert function not working correctly C++

I'm working on a program that uses a binary tree. The program reads from a text file, storing each word in a binary tree alphabetically and finds how many times the word appeared in the file.
The problem I'm having is that my insert function is not working (the program crashes when attempting to run it). I don't know what's exactly wrong, but I suspect it has to do with my else statement towards the end of the function that deals with the right side of the tree.
Any help with fixing it would be appreciated.
Header File
#include <iostream>
#include <string>
using namespace std;
#ifndef TREE_H
#define TREE_H
class Tree
{
public:
Tree();
Tree(string str);
void traversal (Tree *);
void read_file();
void insert(string str);
~Tree();
private:
Tree *left;
Tree *right;
string word;
int count;
};
#endif // TREE_H
Cpp File
#include <iostream>
#include <string>
#include <fstream>
#include "tree.h"
using namespace std;
Tree::Tree()
{
left = NULL;
right = NULL;
count = 0;
}
Tree::Tree(string s)
{
word = s;
}
Tree::~Tree() { }
void Tree::read_file()
{
ifstream myfile;
myfile.open("input.txt", ios::out | ios::in | ios::binary);
if(myfile.is_open()){
while(myfile.good()) {
string buffer;
while(true) {
char c = myfile.get();
if(c == '-' || c == '\'' || isalpha(c) ){
if(isupper(c)) c = tolower(c);
buffer+=c;
}
else break;
}
if(buffer.length() >= 4){
insert(buffer);
}
}
myfile.close();
traversal(this);
}
else { cout << "Unable to open file!" << endl; }
}
void Tree::insert(string str) {
if(str.empty()){ // Also I'm debating whether I need this or not since the string
// cannot possibly be empty as it's part of the condition before
//insert is even called.
this->word = str;
count++;
}
else if(this->word == str) count++;
else if(str < this->word){
if(this->left == NULL) this->left = new Tree(str);
else this->left->insert(str);
}
else {
if(this->right == NULL) this->right = new Tree(str);
else this->right->insert(str);
}
}
void Tree::traversal(Tree *T) {
if(T != NULL) {
traversal(T->left);
cout << T->word << " (" << count << ")" << endl;
traversal(T->right);
}
}
Main
#include <iostream>
#include "tree.h"
using namespace std;
int main()
{
Tree tree;
tree.read_file();
return 0;
}
the problem is that you have 2 constructors, and the second one doesn't initialize pointers left/right to NULL.
edit you are showing properties from different objects: use
cout << T->word << " (" << T->count << ")" << endl;
since the recursive procedure doesn't works calling the member function of the received T. You could do it static, or change it
void Tree::traversal() {
if(this) {
traversal(left);
cout << word << " (" << count << ")" << endl;
traversal(right);
}
}
Personally, I do prefer this last 'style'.
Tree::Tree()
{
word.clear();
left = NULL;
right = NULL;
count = 0;
}
Tree::Tree(string s)
{
word = s;
left = NULL;
right = NULL;
count = 0;
}