When i use this code bellow: exception error is not print out screen when I using g++ in Ubuntu but when i change to Dev C in C++.
#include <iostream>
#include <exception>
#include <stdexcept>
#include <string.h>
#include <sstream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Define Class for exception error
class NoBinaryNumber: public logic_error{
private:
string s;
int x;
public:
NoBinaryNumber(string msg,int x) : logic_error(msg){
s = msg; this->x=x;
}
const char* what() const throw(){
ostringstream a;
a.str("");
a << s << " is wrong at position "<< x;
if(a)
return a.str().c_str();
else
return "";
}
~NoBinaryNumber() throw(){};
};
class BinaryStringToNumber{
public:
int number;
BinaryStringToNumber(string s){
number=0;
for (int i=s.length()-1;i>=0;i--){
if ((s[i]=='1')||(s[i]=='0')){
number=number+(s[i]-'0')*pow(2,i);
}
else{
throw NoBinaryNumber(s,s.length()-i);
cout << "alala" ;
}
}
}
};
int main(){
//Using customer exception error
try{
BinaryStringToNumber a("2");
cout << a.number << endl;
}
catch (NoBinaryNumber& e){
cout << e.what() << endl;
}
return 0;
}
The result shoud be: "2 is wrong at position 1"
In your what() function, you are creating an object (ostringstream), which is destructed at the end of this function call, and trying to access its content (a.str().c_str()) outside of what() function. This is an undefined behaviour (UB) and the fact that DevC++ is showing is just because it is an UB.
To solve this, I suggest you to create your message at constructor call and use what() just to show this message. Something like this:
class NoBinaryNumber: public logic_error{
private:
string s;
int x;
public:
NoBinaryNumber(string msg,int x) : logic_error(msg){
s = msg + " is wrong at position " << std::to_string(x);
this->x=x;
}
const char* what() const throw(){
return msg.c_str();
}
};
Related
This is my code. I created base class and in constructor set x=0. Next I used virtual set_x() = 0. And I created set_x() in new class. Output:
set x
100
DONE. Let's check. 0500
Why I got 0500 not 100500?
#include "mainwindow.h"
#include <QApplication>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
struct invalid_file_handler : std::runtime_error{
using runtime_error::runtime_error;
};
class base_class{
private:
int x;
int y;
public:
virtual void set_x()=0;
void set_y(){
this->y=500;
}
int get_x(){
return (this->x);
}
int get_y(){
return (this->y);
}
base_class(){
this->x=0;
this->y=0;
}
};
class new_class :public base_class{
public:
void set_x();
private:
int z;
int x;
int y;
};
void new_class::set_x(){
cout << "set x " << endl;
this->x=100;
cout << this->x << endl << "DONE. Let's check. ";
}
int main()
{
ifstream my_open_file;
string file_path = "/home/wojtek/Pulpit/elo.odt";
try{
my_open_file.open("/home/wojtek/Pulpit/elo.odt");
my_open_file.close();
}catch (std::runtime_error &e){
cerr << "Hello Xd XD chua" << endl;
cerr << e.what();
}
ofstream myfile;
try{
myfile.open ("/home/wojtek/Pulpit/example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
}
catch(invalid_file_handler &e){
cerr << "Hello!" << endl;
}
new_class *object = new new_class();
object->set_x();
cout << object->get_x();
object->set_y();
cout << object->get_y();
//base_class object;
//cout << object.get_y();
return 0;
}
The variables x and y declared in new_class are shadowing the variables with the same names declared in base_class. This means that in any member method of new_class, the name x refers to new_class::x and not base_class::x.
Simply remove these lines from the new_class definition:
int x;
int y;
And make the same members in the base_class protected instead of private so that the new_class also has access:
class base_class{
protected:
int x;
int y;
Note: your code has a memory leak, since you never delete object after allocating it. Always delete what you new, and don't use new unless you really need to.
I am trying to compile this project just to see how I am doing as I go along, but I still have a few more classes to implement that will inherit from Widget for different types. When I compile I keep getting C2678:
Error C2678 binary '==': no operator found which takes a left-hand
operand of type 'Widget' (or there is no acceptable conversion)
Assignment10 c:\program files (x86)\microsoft visual
studio\2017\community\vc\tools\msvc\14.11.25503\include\xutility line3107
I cant find where this error is thrown or why. Any help would be greatly appreciated. Sorry it's so sloppy, I've been messing with it a lot to try and find the problem.
#pragma once
#include <iostream>
using namespace std;
class Widget
{
public:
int idNumber;
//structors
Widget()
{
idNumber = 0;
}
Widget(int a)
{
idNumber = a;
}
~Widget();
//operations
int getId()
{
return idNumber;
}
//overload operators to compare idNumber
void operator= (Widget &rhs)
{
idNumber = rhs.idNumber;
}
};
----------------------------------------
#include "Widget.h"
#include <iostream>
using namespace std;
Widget::~Widget()
{
}
/*
bool Widget::operator< (Widget &rhs)
{
bool result;
result = idNumber < rhs.idNumber;
return result;
}*/
---------------------------------
#pragma once
#include "Widget.h"
#include <list>
#include <iostream>
using namespace std;
class Inventory
{
public:
Inventory();
Inventory(int i)
{
Widget w(i);
}
~Inventory();
//operations
//process order for shipment
void order(int widgID);
//recieve widget
void receive(int widgID);
//overlaod output operator
friend ostream& operator<<(ostream&, const Widget&);
protected:
list<Widget> onHand;
list<int> onOrder;
};
-------------------------------
#include "Inventory.h"
#include "Widget.h"
#include <iostream>
#include <list>
using namespace std;
Inventory::Inventory()
{
Widget w;
}
Inventory::~Inventory()
{
}
//recieve widget
void Inventory::receive(int widgID)
{
cout << " Recieved shipment of Widget type "
<< widgID << endl;
//find the iterator of the widget location
list<int>::iterator weNeed;
weNeed = find(onOrder.begin(), onOrder.end(), widgID);
//if end is returned, item not found
if (weNeed != onOrder.end())
{
cout << "Ship " << Widget(widgID) << " to fill back order" << endl;
onOrder.erase(weNeed);
}
else
{
onHand.push_front(Widget(widgID));
}
}
//process order
void Inventory::order(int widgID)
{
cout << " Recieved order for Widget type "
<< widgID << endl;
//find the iterator of the widget location
list<Widget>::iterator weHave;
weHave = find(onHand.begin(), onHand.end(), widgID);
//if end is returned, item not found
if (weHave != onHand.end())
{
cout << "Ship " << *weHave << endl;
onHand.erase(weHave);
}
else
{
cout << "Back order widget of type "
<< widgID << endl;
onHand.push_front(Widget(widgID));
}
}
ostream& operator<<(ostream& os, const Widget& wid)
{
os << wid.idNumber;
return os;
}
I am new to c++ and I'm having a bit of trouble implementing my first program. I need to create a Line class which simply contains an array of char (c-string) as well as a length and a max capacity. The linePtr member variable is of type char*. Here is what I have:
Line.h:
#pragma once
#ifndef LINE_H
#define LINE_H
#include <iostream>
using namespace std;
class Line {
private:
char* linePtr{nullptr};
int lineLength;
int lineCapacity;
public:
Line(); //default ctor
Line(char);
~Line();
friend ostream& operator<<(ostream& output, const Line& l);
};
#endif // !LINE_H
Line.cpp:
#include <iostream>
#include <cstring>
#include "Line.h"
using std::cout;
using std::endl;
using std::strcpy;
using std::strlen;
const int LINE_CAPACITY = 5000; //arbitrarily set
Line::Line() {
cout << "Default ctor" << endl;
linePtr = new char[1]{ '\0' };
lineCapacity = LINE_CAPACITY;
lineLength = 0;
}
Line::Line(char cstr) {
cout << "ctor Line(char cstr)" << endl;
linePtr = new char[2];
lineCapacity = LINE_CAPACITY;
lineLength = 1;
linePtr[0] = cstr;
}
ostream& operator<<(ostream& out, const Line& l) {
return out << l.linePtr;
}
Main.cpp:
#include <iostream>
#include "Line.h"
using namespace::std;
int main() {
Line l1;
cout << l1 << endl;
Line l2('x');
cout << l2 << endl;
system("pause");
return 0;
}
When I run with debugging, when the linePtr field it is written I get the message: "Error reading characters of string". I'm sure I'm doing something stupid but I can't figure it out.
You're not null-terminating the character array in the second constructor. Add this line at the end of the method:
linePtr[1] = '\0';
I am getting a linker error undefined reference to Person::Person when trying to implement my program. The three parts are below. I have been working on fixing it for a few hours now. I know it's probably something simple that I am just not seeing. But I have looked around on the internet and still have not found my answer. So any help would be appreciated.
#ifndef PERSON0_H_
#define PERSON0_H_
#include <string>
class Person // class declaration
{
private:
static const int LIMIT = 25;
std::string lname;
char fname[LIMIT];
public:
Person() {lname = ""; fname[0] = '\0';}
Person(const std::string & ln, const char * fn = "Hay you");
void Show() const;
void FormalShow() const;
};
#endif
#include <iostream>
#include <string>
#include "person0.h"
void Person::Show() const
{
using namespace std;
std::cout << fname << " " << lname << '\n';
}
void Person::FormalShow() const
{
using std::cout;
std::cout << lname << ", " << fname << '\n';
}
#include <iostream>
#include <string>
#include "person0.h"
int main()
{
using namespace std;
Person one;
Person two("Smythecraft");
Person three("Dimwiddy", "Sam");
one.Show();
cout << endl;
one.FormalShow();
cout << endl;
two.Show();
cout << endl;
two.FormalShow();
cout << endl;
three.Show();
cout << endl;
three.FormalShow();
cin.get();
cin.get();
return 0;
}
I am not really a C++ person, so the terminology might be wrong, but I would say that the implementation of the
Person::Person(const std::string & ln, const char * fn)
constructor is missing.
Header file
#include <iostream>
#include <cstring>
const unsigned MaxLength = 11;
class Phone {
public:
Phone(const char *phone) {
setPhone(phone);
}
void setPhone(const char Phone[ ]);
const char* getPhone();
private:
char phone[MaxLength+1];
};
Cpp file
#include "Phone.h"
#include <iostream>
#include <ctype.h>
#include <cstring>
using namespace std;
bool checkNum(char num[]);
void Phone::setPhone(const char Phone[ ]) {
strncpy(phone, Phone, MaxLength);
phone[MaxLength] = '\0';
}
const char* Phone::getPhone() {
return phone;
}
int main() {
Phone i1("12345678901");
cout << i1.getPhone() << endl;
if (checkNum(i1.getPhone))
cout << "Correct" << endl;
else
cout << "Invalid Wrong" << endl;
}
bool checkNum(char num[]) {
bool flag = true;
if (isdigit(num[0]) == 0)
flag = false;
return flag;
}
When I tried to compile, I get this error:
error C3867: 'Phone::getPhone':
function call missing argument list;
use '&Phone::getPhone' to create a
pointer to member
I'm getting an error on this line "if (checkNum(i1.getPhone))". I created a Phone object and what I am trying to do is use the function checkNum to see if the first index of the array is a number. Am I referencing the object wrong? Should I use indirect selection operator instead? Any idea what I am doing wrong?
Thanks
You are missing a pair of parentheses after getPhone in if (checkNum(i1.getPhone)); it should be if (checkNum(i1.getPhone())).
The line:
if (checkNum(i1.getPhone))
should be
if (checkNum(i1.getPhone()))