in my school assignment i need a small help
this is my header file:
#include <iostream>
#include <cstring>
using namespace std;
#include "ISBNPrefix.h"
class ISBN
{
char str[11];
char area[6];
char publisher[8];
char title[7];
bool registered;
public:
ISBN();
ISBN(const char*,ISBNPrefix &);
void toStr(char*)const;
void toStrWithStyle(char*)const;
bool empty()const;
bool isRegistered() const;
bool read(istream& is, const ISBNPrefix& list);
void display(ostream&) const;
};
int isValid(const char* str);
and this is the implementation of my file:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <iomanip>
using namespace std;
#include "ISBN.h"
ISBN::ISBN()
{
str[0]='\0';
area[0]='\0';
publisher[0]='\0';
title[0]='\0';
registered=false;
}
ISBN::ISBN(const char* s,ISBNPrefix& p)
{
if(isValid(s)==1)
{
strcpy_s(str,s);
}
else
{
*this=ISBN();
}
}
bool ISBN::empty()const
{
bool chk=false;
if(str[0]=='\0')
chk=true;
return chk;
}
void ISBN::toStrWithStyle(char* s) const
{
if(registered)
{
sprintf(s,"%s-%s-%s-%c",area,publisher,title,str[9]);
}
else
{
toStr(s);
}
}
void ISBN::toStr(char* s) const
{
if (str[0]!='\0')
strcpy(s,str);
else
strcpy(s,"no data");
}
void ISBN::display(ostream & os) const
{
char str[14];
toStrWithStyle(str);
cout<< setw (13) <<str;
}
int isValid(const char* str)
{
int rc=0;
if(str!=0)
{
int sum,i=0;
sum=0;
for(i=0;i<10;i++)
sum+=(str[i]-'0')*(10-i);
if(sum%11==0)
{
rc= 1;
}
}
else
rc=0;
return rc;
}
bool ISBN::read(istream& is, const ISBNPrefix& list)
{
char str[11];
bool quit=false;
bool ok=false;
char lists;
do{
cout<<"ISBN (0 to quit) : ";
is.getline(str,11); //or is.get(str,11)
if(strcmp(str,"0")==0)
quit=true;
else if (isValid(str)==1)
{
*this=ISBN(str,list);
ok=true;
cout<<"isbn is valid"<<endl;
}
else
{
*this=ISBN();
cout<<"invalid ISBN"<<endl;
}
} while(!quit&&!ok);
return !quit;
}
in the ISBN::read where I say
*this=ISBN(str,list);
i want to overload another member but i can't.
can anyone tell me how can i do that?
First I would suggest use std::string in favour of char[]. It will save a lot of trouble. For reading ISBN I would write something like this:
bool ISBN::read(istream& is)
{
ISBN result;
// reading into result
std::swap(*this,result);
return !quit;
}
Or even better (as a non member function):
std::istream& operator>>(istream& is, ISBN& obj)
{
ISBN result;
// reading into result
is(!quit)
is.clear(std::ios_base::failbit);
std::swap(obj,result);
return is;
}
In any way you should RAII classes for your resources. In your special case std::string instead of char[].
Related
So I implemented Stack basic operations in c++.I wrote the functions but I don't know how to implement the main the function such that to see the values from the stack.
header file
#ifndef HEADER_H_
#define HEADER_H_
#define DIM 15
typedef int Atom;
struct Element {
Atom data;
Element *link;
};
typedef Element* LinkedStack;
void initS(LinkedStack &S);
void push(LinkedStack &S, Atom a);
bool isEmpty2(LinkedStack &S);
void pop2(LinkedStack &S);
Atom top2(Stack &S);
#endif
The functions file
void initS(LinkedStack &S)
{
S = nullptr;
}
void push(LinkedStack &S, Atom a)
{
Element*nou = new Element;
nou->data = a;
nou->link = S;
S = nou;
}
bool isEmpty2(LinkedStack &S)
{
if (S == 0)
return true;
else return false;
}
void pop2(LinkedStack &S)
{
LinkedStack aux = S;
S = S->link;
delete(aux);
}
Atom top2(LinkedStack &S)
{
if (isEmpty2(S))
return Atom();
return S->data;
}
How I implemented the main function.I don't know how to see values, for example if I write cout<
#include <iostream>
#include "header.h"
using namespace std;
int main()
{
LinkedStack S;
initS(S);
push(S, 2);
push(S, 4);
push(S, 6);
push(S, 7);
push(S, 10);
return 0;
}
After I compile the program I don't see nothing in console.How to see the values from stack?
I need to print the vector i have filled in listInput. When i go to listPrint the program crashes. What can i do to fix it? Here is my main:
#include <iostream>
#include <string>
#include <vector>
#include "func.h"
using namespace std;
int main(int argc, char** argv) {
subjects a;
int r=1;
while(r!=0){
int select=a.userChoice();
switch(select){
case 1:
a.listPrint();
break;
case 2:
listInput(a);
break;
}
}
return 0;
}
My header:
#ifndef SUBJECT
#define SUBJECT
#include <string>
#include <vector>
class subjects{
private:
std::string subjectName;
std::string lectName;
std::string lectSurname;
int credits;
int studentnum;
public:
/* subjects(){
subjectName="";
lectName="";
lectSurname="";
credits=0;
studentnum=0;
}*/
int userChoice();
int enterNumber(std::string name);
void menu();
std::string getSubjectName(){
return subjectName;
}
std::string getLectName(){
return lectName;
}
std::string getLectSurname(){
return lectSurname;
}
int getCredits(){
return credits;
}
int getStudentNum(){
return studentnum;
}
friend void listInput(subjects a);
void listPrint();
bool checkName(std::string &text);
std::vector<subjects*> entry;
subjects(const std::string subjectName="", const std::string lectName = "", const std::string lectSurname="", const int credits = 0, const int studentnum = 0) :
subjectName(subjectName),
lectName(lectName),
lectSurname(lectSurname),
credits(credits),
studentnum(studentnum){
}
};
#endif
And my function file:
void listInput(subjects a){
.
.
.
a.entry.push_back(new subjects(a.subjectName, a.lectName,a.lectSurname,a.credits, a.studentnum));
}
void subjects::listPrint(){
for(int i=0; i<entry.size(); i++){
cout<<entry[i]->getSubjectName()<<" "<<entry[i]->getLectName()<<" "<<entry[i]->getLectSurname()<<" "<<entry[i]->getCredits()<<" "<<entry[i]->getStudentNum()<<endl;
}
}
I know that using friend functions arent recommended, but i am required to use atleast one of them. Also if i print the vector in listInput, then it only prints the first entry. If there is more than one entry in the vector, it also crashes.
You pass the a instance by value to the list function and then you try to print it. You should consider passing it by reference if you plan to use it outside the scope of the list function.
Here is my program
Contact.h
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
#pragma once
class Contact
{
private:
char *Name;
char *Last;
int Phone;
char *Address;
public:
Contact operator +(Contact NewVal);
Contact(char *newName,char *newLastName,char *newAddress,int newPhone);
Contact(void);
~Contact(void);
void SetName(char *newName);
void SetLastName(char *newLastName);
void SetAddress(char *newAddress);
void SetPhone(int newPhone);
char* Contact::GetLast(void);
char* Contact::GetAddress(void);
int Contact::GetPhone(void);
char* GetName(void);
};
Contact.cpp
#include "StdAfx.h"
#include "Contact.h"
Contact::Contact(void)
{
}
Contact::Contact(char *newName,char *newLastName,char *newAddress,int newPhone)
{
SetName(newName);
SetLastName(newLastName);
SetAddress(newAddress);
SetPhone(newPhone);
}
Contact::~Contact(void)
{
}
void Contact::SetName(char *newName){
Name=_strdup(newName);
}
void Contact::SetLastName(char *newLastName){
Last=strdup(newLastName);
}
void Contact::SetAddress(char *newAddress){
Address=strdup(newAddress);
}
void Contact::SetPhone(int newPhone){
Phone=newPhone;
}
char* Contact::GetName(void)
{
return Name;
}
char* Contact::GetLast(void)
{
return Last;
}
char* Contact::GetAddress(void)
{
return Address;
}
int Contact::GetPhone(void)
{
return Phone;
}
Contact Contact::operator+(Contact NewVal)
{
//strcat(this->Address,NewVal.Address);
//strcat(this->Last,NewVal.Last);
//strcat(this->Name,NewVal.Name);
this->Phone=this->Phone+NewVal.Phone;
sprintf(this->Address,"%s %s",this->Address,NewVal.Address);
sprintf(this->Name,"%s %s",this->Name,NewVal.Name);
sprintf(this->Last,"%s %s",this->Last,NewVal.Last);
return *this;
}
Phonebook.h
#include "Contact.h"
#pragma once
class PhoneBook
{
private:
Contact member[100];
int ID;
public:
PhoneBook(void);
~PhoneBook(void);
Contact Search(char* newName);
bool AddNewContact(char* NewName, char* NewLast, char* NewAddress,int NewPhone);
void ShowContacts(void);
};
PhoneBook.Cpp
#include "StdAfx.h"
#include "PhoneBook.h"
PhoneBook::PhoneBook(void)
{
}
PhoneBook::~PhoneBook(void)
{
}
Contact PhoneBook::Search(char* newName)
{
return Contact();
}
bool PhoneBook::AddNewContact(char* NewName, char* NewLast, char* NewAddress,int NewPhone)
{
ID=ID+1;
member[ID].SetName(NewName);
member[ID].SetLastName(NewLast);
member[ID].SetAddress(NewAddress);
member[ID].SetPhone(NewPhone);
return true;
}
void PhoneBook::ShowContacts(void)
{
for(int a=0;a<=ID;a++){
cout<<"Name:"<<member[ID].GetName()<<endl<<"LastName:"<<member[ID].GetLast()<<endl<<"Address:"<<member[ID].GetAddress()<<endl<<"Phone:"<<member[ID].GetPhone()<<endl;
}
}
After executing these lines I get access violation error(for SetName function)
int _tmain(int argc, _TCHAR* argv[])
{
PhoneBook mem;
mem.AddNewContact("Bob","Jones","LA",100);
return 0;
}
However this code works fine!!! it means Set functions in Contact.h file work without any problems but after adding the Phonebook class it won't work.
int _tmain(int argc, _TCHAR* argv[])
{
PhoneBook mem;
Contact no("Bob","Jones","LA",100);
//mem.AddNewContact("Bob","Jones","LA",100);
return 0;
}
I will be grateful if you can help me.
Sorry for my mistake. I've forgotten to set a default value for ID variable.
Thanks Steve and Gray for your comments.
I've been pulling my hair out over a certain error that seems to be plaguing my program. I've attempted to search online for cases similar to mine but I can't seem to find a way to apply the other solutions to this problem. My issue is as follows: When I initially open the program it immediately stops responding and crashes. Debugging led me to find the error in question is "0xC0000005: Access violation writing location 0xCCCCCCCC". It seems to be tied to me assigning two attributes (sku_ and name_ ) as '\0'. If I change these values to anything else such as "" or even "\0" the program runs in visual studio, but will fail to compile elsewhere. Could someone help me understand where I am going wrong?
Product.h
#ifndef SICT_Product_H__
#define SICT_Product_H__
#include "general.h"
#include "Streamable.h"
#include <cstring>
namespace sict {
class Product : public Streamable {
char sku_ [MAX_SKU_LEN + 1];
char* name_;
double price_;
bool taxed_;
int quantity_;
int qtyNeeded_;
public:
//Constructors
Product();
Product(const char* sku, const char* name1, bool taxed = true, double price = 0, int qtyNeeded =0);
Product(Product& g);
~Product();
//Putter Functions
void sku(const char* sku) { strcpy(sku_,sku); };
void price(double price) {price_ = price;};
void name(const char* name);
void taxed(bool taxed) { taxed_ = taxed; };
void quantity(int quantity) { quantity_ = quantity; };
void qtyNeeded(int qtyNeeded) { qtyNeeded_ = qtyNeeded; };
//Getter functions
const char* sku() const { return sku_; };
double price() const { return price_; };
const char* name() const { return name_; };
bool taxed() const { return taxed_; };
int quantity() const { return quantity_; };
int qtyNeeded() const { return qtyNeeded_; };
double cost() const;
bool isEmpty() const;
Product& operator=(const Product& );
bool operator==(const char* );
int operator+=(int );
int operator-=(int );
};
double operator+=(double& , const Product& );
std::ostream& operator<<(std::ostream& os, const Product& );
std::istream& operator>>(std::istream& is, Product& );
}
#endif
Product.cpp
#include <iostream>
#include <cstring>
#include "Product.h"
namespace sict {
Product::Product() {
sku_[0] = '\0';
name_[0] = '\0';
price_ = 0;
quantity_ = 0;
qtyNeeded_ = 0;
}
Product::Product(const char* sku, const char* name1, bool taxed1, double price1, int qtyNeeded1) {
strncpy(sku_, sku, MAX_SKU_LEN);
name(name1);
quantity_ = 0;
taxed(taxed1);
price(price1);
qtyNeeded(qtyNeeded1);
}
double Product::cost() const {
if (taxed_ == true) {
return (price_ * TAX) + price_;
}
else
return price_;
}
bool Product::isEmpty() const{
if (sku_ == nullptr && name_ == nullptr && quantity_ == 0 && price_ == 0 && qtyNeeded_ == 0) {
return true;
}
else
return false;
}
Product::Product(Product& ex) {
sku(ex.sku_);
price(ex.price_);
name(ex.name_);
taxed(ex.taxed_);
quantity(ex.quantity_);
qtyNeeded(ex.qtyNeeded_);
}
Product& Product::operator=(const Product& g) {
sku(g.sku_);
price(g.price_);
name(g.name_);
taxed(g.taxed_);
quantity(g.quantity_);
qtyNeeded(g.qtyNeeded_);
return *this;
}
Product::~Product() {
delete [] name_;
}
void Product::name(const char* name) {
name_ = new char [strlen(name) + 1];
strcpy(name_, name);
}
bool Product::operator==(const char* right) {
if (sku_ == right) {
return true;
}
else
return false;
}
int Product::operator+=(int g) {
quantity_ = quantity_ + g;
return quantity_;
}
int Product::operator-=(int g) {
quantity_ = quantity_ - g;
return quantity_;
}
double operator+=(double& p, const Product& right) {
p = p + (right.cost() * right.quantity());
return p;
}
std::ostream& operator<<(std::ostream& os, const Product& g) {
return g.write(os, true);
}
std::istream& operator>>(std::istream& is, Product& g) {
return g.read(is);
}
}
The General.h file referenced in the header is just a list of constant values such as the "TAX" and "MAX_SKU_LEN" values.
The Streamable header contains pure virtual functions. I will list it here in case it is needed.
Streamable.h
#ifndef SICT__Streamable_H_
#define SICT__Streamable_H_
#include <iostream>
#include <fstream>
#include "Product.h"
namespace sict {
class Streamable {
public:
virtual std::fstream& store(std::fstream& file, bool addNewLine = true)const = 0;
virtual std::fstream& load(std::fstream& file) = 0;
virtual std::ostream& write(std::ostream& os, bool linear)const = 0;
virtual std::istream& read(std::istream& is) = 0;
};
}
#endif
Thank you very much in advance.
Product::Product() {
sku_[0] = '\0';
name_[0] = '\0'; // <---- writing via unitialized pointer
price_ = 0;
quantity_ = 0;
qtyNeeded_ = 0;
}
There's one possible source of your problems. You have defined a char pointer (a dynamic array or a C-string, that is) name_ in your class but you never allocate any memory for it in your constructor, before attempting to record a value via the pointer. Naturally, you get a write access violation.
Before assigning the value to char at index [0] you need to first allocate space for at least one element in your string, e.g. by doing name_ = new char [1]. Alternatively, you may choose to initialize the pointer itself to NULL (or nullptr) and use that to indicate that name_ has not yet been set.
i am working on a program that reads in a text file that the user inputs, creates a text file that the user inputs, names the text file that the user wants, and then sorts the text file sorting words above the user entered in threshold and displays the words and how many times it was found to the output file the user specify's. i have most of the code finished but im getting a compiler error heres the sample output, error and code
sample output
Enter name of input command file; press return.
history.in
Enter name of output file; press return.
history.out
Enter name of test run; press return.
sample
Enter the minimum size word to be considered.
5
Sample results (found in user specified output file):
sample
abacus 4
abstract 1
adding 1
addition 2
advances 1
after 3
where the word is the word found in the text file, and the number next to it is how many times it was found.
The compiler errors are:
C:\Users\kevin jack\Desktop\prog-4>g++ -o try main.cpp
main.cpp:(.text+0x329) undefined reference to `StrType::PrintToFile(bool, std::basic_ofstream<char, std::char_traits<char> >&)'
:main.cpp:(.text+0x608): undefined reference to `StrType::GetStringFile(bool, InType, std::basic_ifstream<char, std::char_traits<char> >&)'
main.cpp:(.text+0x639): undefined reference to `StrType::LenghtIs()'
main.cpp:(.text+0x6d8): undefined reference to `StrType::GetStringFile(bool, InType, std::basic_ifstream<char, std::char_traits<char> >&)'
collect2: ld returned 1 exit status
i have no idea what this means if anyone knows please inform me here is my code
main.cpp
//main.cpp
#include <fstream>
#include "StrType.h"
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
struct WordType
{
public:
StrType word;
int count;
};
struct TreeNode
{
WordType info;
TreeNode* left;
TreeNode* right;
};
class ListType
{
public:
ListType();
void InsertOrIncrement (StrType string);
void Print(std::ofstream&) const;
private:
TreeNode* root;
};
ListType::ListType()
{
root=NULL;
}
void Process(TreeNode*& tree, StrType s)
{
if(tree == NULL)
{
tree = new TreeNode;
tree->info.word = s;
tree->info.count = 1;
tree->left = NULL;
tree->right = NULL;
}
else if (tree->info.word == s)
tree->info.count++;
else if (s < tree->info.word)
Process(tree->left, s);
else
Process(tree->right, s);
}
void ListType::InsertOrIncrement(StrType s)
{
Process(root, s);
}
void Print (TreeNode* tree, std::ofstream& outFile)
{
if (tree!= NULL)
{
Print(tree->left, outFile);
tree->info.word.PrintToFile(true, outFile);
outFile <<" "<< tree->info.count;
Print(tree->right, outFile);
}
}
void ListType::Print(std::ofstream& outFile) const
{
::Print(root, outFile);
}
int main()
{
using namespace std;
ListType list;
string inFileName;
string outFileName;
string outputLabel;
ifstream inFile;
ofstream outFile;
StrType string;
int minimumLenght;
cout<<"enter in imput file name."<<endl;
cin>>inFileName;
inFile.open(inFileName.c_str());
cout<<"enter name of output file."<<endl;
cin>>outFileName;
outFile.open(outFileName.c_str());
cout<<"enter name of test run."<<endl;
cin>>outputLabel;
outFile<< outputLabel << endl;
cout<<"enter the min word size."<<endl;
cin>>minimumLenght;
string.GetStringFile(true, ALPHA_NUM, inFile);
while(inFile)
{
if(string.LenghtIs() >= minimumLenght)
list.InsertOrIncrement(string);
string.GetStringFile(true, ALPHA_NUM, inFile);
}
list.Print(outFile);
outFile.close();
inFile.close();
return 0;
}
StrType.h
//StrType.h
#include <fstream>
#include <iostream>
const int MAX_CHARS=100;
enum InType{ALPHA_NUM, ALPHA, NON_WHITE, NOT_NEW};
class StrType
{
public:
void MakeEmpty();
void GetString(bool skip, InType charsAllowed);
void GetStringFile(bool skip, InType charsAllowed,
std::ifstream& inFile);
void PrintToScreen(bool newLine);
void PrintToFile(bool newLine, std::ofstream& outFile);
int LenghtIs();
void CopyString(StrType& newString);
bool operator==(const StrType& other) const;
bool operator<(const StrType& other) const;
private:
char letters[MAX_CHARS + 1];
};
bool StrType::operator==(const StrType& other) const
{
return (strcmp(letters, other.letters) == 0);
}
bool StrType::operator<(const StrType& other) const
{
return (strcmp(letters, other.letters) < 0);
}
void StrType::MakeEmpty()
{
letters[0] ='\0';
}
what i was trying to overload the == and > operator. i am stating it in class StrType and defining it just below it but im not sure if im defining it correctly or even in the right spot! any help would be greatly appreciated
If you want to compile and check your code, you should define all member functions of all classes at least as (nearly) empty functions.
void StrType::GetString(bool skip, InType charsAllowed)
{
// empty function, you will write your code heree later
}
// ...
Don't forget about return-values for non-void functions
notMine.cpp
//StrType.h
#include <fstream>
#include <iostream>
const int MAX_CHARS=100;
enum InType{ALPHA_NUM, ALPHA, NON_WHITE, NOT_NEW};
class StrType
{
public:
void MakeEmpty();
void GetString(bool skip, InType charsAllowed)
{
}
void GetStringFile(bool skip, InType charsAllowed, std::ifstream& inFile)
{
}
void PrintToScreen(bool newLine)
{
}
void PrintToFile(bool newLine, std::ofstream& outFile)
{
}
int LenghtIs()
{
return 0;
}
void CopyString(StrType& newString)
{
}
bool operator==(const StrType& other) const
{
return (strcmp(letters, other.letters) == 0);
}
bool operator<(const StrType& other) const
{
return (strcmp(letters, other.letters) < 0);
}
private:
char letters[MAX_CHARS + 1];
};
void StrType::MakeEmpty()
{
letters[0] ='\0';
}
myOwnSomething.h
#include <stdio.h>
#include <fstream>
#include <cstddef>
#include <iostream>
#include <string>
#include "myOwnSomething.h"
using namespace std;
struct WordType
{
public:
StrType word;
int count;
};
struct TreeNode
{
WordType info;
TreeNode* left;
TreeNode* right;
};
class ListType
{
public:
ListType();
void InsertOrIncrement (StrType string);
void Print(std::ofstream&) const;
private:
TreeNode* root;
};
ListType::ListType()
{
root=NULL;
}
void Process(TreeNode*& tree, StrType s)
{
if(tree == NULL)
{
tree = new TreeNode;
tree->info.word = s;
tree->info.count = 1;
tree->left = NULL;
tree->right = NULL;
}
else if (tree->info.word == s)
tree->info.count++;
else if (s < tree->info.word)
Process(tree->left, s);
else
Process(tree->right, s);
}
void ListType::InsertOrIncrement(StrType s)
{
Process(root, s);
}
void Print (TreeNode* tree, std::ofstream& outFile)
{
if (tree!= NULL)
{
Print(tree->left, outFile);
tree->info.word.PrintToFile(true, outFile);
outFile <<" "<< tree->info.count;
Print(tree->right, outFile);
}
}
void ListType::Print(std::ofstream& outFile) const
{
::Print(root, outFile);
}
int main()
{
using namespace std;
ListType list;
string inFileName;
string outFileName;
string outputLabel;
ifstream inFile;
ofstream outFile;
StrType string;
int minimumLenght;
cout<<"enter in imput file name."<<endl;
cin>>inFileName;
inFile.open(inFileName.c_str());
cout<<"enter name of output file."<<endl;
cin>>outFileName;
outFile.open(outFileName.c_str());
cout<<"enter name of test run."<<endl;
cin>>outputLabel;
outFile<< outputLabel << endl;
cout<<"enter the min word size."<<endl;
cin>>minimumLenght;
string.GetStringFile(true, ALPHA_NUM, inFile);
while(inFile)
{
if(string.LenghtIs() >= minimumLenght)
list.InsertOrIncrement(string);
string.GetStringFile(true, ALPHA_NUM, inFile);
}
list.Print(outFile);
outFile.close();
inFile.close();
return 0;
}