Not sure why my program wont display - c++

#include <iostream>
#include <string>
using namespace std;
class BookData
{
string Title;
int Qty;
public:
void setTitle(string in_title) { Title = in_title;}
string setQty(int in_qty) { Qty = in_qty; }
string getTitle() { return Title; }
int getQty() { return Qty; }
};
int main()
{
BookData book;
book.setTitle("Starting Out with C++");
book.setQty(10);
cout << "Title is " << book.getTitle() << ".\n\n";
cout << "Quantity is " << book.getQty() << ".\n\n";
return 0;
}
When I compile all I get is an empty console. Any suggestions?

Change the return type of BookData::setQty() from string to void.
Without this change, it should still work fine. On my Linux machine, it crashes when setQty() is called with a return type of string and no string being returned.

Does the console close immediately? If so, put this before return 0;:
System("PAUSE");
Or:
std::cin.ignore();
Or (for MSVC++2010):
int temp;
std::cin >> temp;

Related

My getlines are showing an error as well as my get functions when I put in a variable in the parentheses c++

I have a banking project and I am trying to set up the bank name, address, and working hours. My getlines are showing an error as well as my get functions.
Input exact error messages here please.
'getline': no matching overloaded function found
no suitable user-defined conversion from "Bank" to "std::string" exists
Here's the class for bank:
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cctype>
#include <cstdlib>
using namespace std;
class Bank {
public:
void setBankName(string bn) { bn = bankname; }
string getBankName() { return bankname; }
void setBankAdd(string ba) { ba = bankadd; }
string getBankAdd() { return bankadd; }
void setWorkingHours(string bwh) { bwh = bankworkinghours; };
string getWorkingHours() { return bankworkinghours; }
private:
string bankname, bankadd, bankworkinghours;
};
//and then this is in my main function
int main() {
Bank bankname, bankadd, bankworkinghours;
char userChoice; // numbers 1-9
int number=0;
system ("color 5f");
cout << "Name of bank: ";
getline(cin, bankname); **//all the get lines also show error**
cout << endl;
cout << "Bank address: ";
getline(cin, bankadd);
cout << endl;
cout << "Bank working hours: ";
getline(cin, bankworkinghours);
cout << endl;
bankname.setBankName(bankname); //the things in the parentheses show error
bankadd.setBankAdd(bankadd);
bankworkinghours.setWorkingHours(bankworkinghours);
The error is self explanatory. 2nd parameter of getline function is std:string so define bankname as std:string and then set the name of bank object by setBankName.
1- You did not created bank Object in the main to set class attributes.
You need an Object with reference to that object you will set the parameters of the class bank.
2- bankname, bankadd, bankworkinghours are string and you made them Bank
Here is updated code and working fine in VS 2019 without any error. Just a few changes in the first 2 and last three lines of main
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cctype>
#include <cstdlib>
using namespace std;
class Bank {
public:
void setBankName(string bn) { bn = bankname; }
string getBankName() { return bankname; }
void setBankAdd(string ba) { ba = bankadd; }
string getBankAdd() { return bankadd; }
void setWorkingHours(string bwh) { bwh = bankworkinghours; };
string getWorkingHours() { return bankworkinghours; }
private:
string bankname, bankadd, bankworkinghours;
};
//and then this is in my main function
int main() {
Bank bankObj;
string bankname, bankadd, bankworkinghours;
char userChoice; // numbers 1-9
int number = 0;
system("color 5f");
cout << "Name of bank: ";
getline(cin, bankname);
cout << endl;
cout << "Bank address: ";
getline(cin, bankadd);
cout << endl;
cout << "Bank working hours: ";
getline(cin, bankworkinghours);
cout << endl;
bankObj.setBankName(bankname);
bankObj.setBankAdd(bankadd);
bankObj.setWorkingHours(bankworkinghours);
}
void setBankName(string bn) { bn = bankname; } is the wrong way around. try bankname = bn.

Using an enum from a class (C++)

I'm reading a book on C++ and was writing out some code to practice using the interface and implementation of a class. I've searched for solutions to my issue for a while to no avail.
I have a class with an enumeration inside of it. While trying to instantiate an object of that class, I am having trouble accessing the enum types outside of the class. I have tried using Book::Horror, Biblo::Horror, Biblo::Book::Horror, Horror, and even things like Biblo::Book::Genre::Horror. Can't seem to get it to let me access the types of the enum for the instantiation of my object in the main.cpp file.
Any help is appreciated! The more complex uses of C++ are still new to me. Here is my source:
book.h
#include <iostream>
#include <string>
using namespace std;
namespace Biblo{
class Book{
public:
enum Genre{
No_Genre, Horror, Comedy, Romance, Mystery
};
// The rest of this header is working fine I think, just this enum
class Invalid{}; // Used for throwing errors
Book(int n_ISBN, int n_copyrightYear, string n_title, string n_author, Genre n_genre);
Book();
// Accessors (non-modifying)
int getISBN() const { return ISBN; }
int getCopyrightYear() const { return copyrightYear; }
string getTitle() const { return title; }
string getAuthor() const { return author; }
string getGenre() const;
// Mutators
void changeAuthor(string newAuthor);
private:
int ISBN;
int copyrightYear;
string title;
string author;
Genre genre;
}; // End Book
// Helper Functions go here
bool operator==(const Book& a, const Book& b);
bool operator!=(const Book& a, const Book& b);
} // End Biblo
and main.cpp
#include <iostream>
#include "book.h"
using namespace std;
int main()
{
Biblo::Book book(100, 2012, "The Walrus", "The Eggman", Book::Horror); // THIS LINE GIVES ERROR
cout << "ISBN: " << book.getISBN() << endl;
cout << "Copyright: " << book.getCopyrightYear() << endl;
cout << "Title: " << book.getTitle() << endl;
cout << "Author: " << book.getAuthor() << endl;
cout << "Genre: " << book.getGenre() << endl;
return 0;
}
Edit: here is the book.cpp file
#include <iostream>
#include "book.h"
#include <string>
namespace Biblo{
Book::Book(int n_ISBN, int n_copyrightYear, string n_title, string n_author, Genre n_genre)
:ISBN(n_ISBN), copyrightYear(n_copyrightYear), title(n_title), author(n_author), genre(n_genre)
{
// constructor
}
Book::Book()
:ISBN(0), copyrightYear(0), title(""), author(""), genre(Genre::No_Genre)
{
// Default constructor
}
// Accessors
string Book::getGenre() const
{
if (Book.genre == Genre::No_Genre)
return "No Genre!";
if (Book.genre == Genre::Horror)
return "Horror";
if (Book.genre == Genre::Comedy)
return "Comedy";
if (Book.genre == Genre::Romance)
return "Romance";
if (Book.genre == Genre::Mystery)
return "Mystery";
}
// Mutators
void Book::changeAuthor(string newAuthor)
{
author = newAuthor;
}
// Helper Functions
bool operator==(const Book& a, const Book& b)
{
if (a.getISBN() != b.getISBN())
return false;
if (a.getCopyrightYear() != b.getCopyrightYear())
return false;
if (a.getTitle() != b.getTitle())
return false;
if (a.getAuthor() != b.getAuthor())
return false;
if (a.getGenre() != b.getGenre())
return false;
return true;
}
bool operator!=(const Book& a, const Book& b)
{
return !(a==b);
}
} // End Biblo
It seems you tried everything but the thing you needed! The enum is nested inside the Book class which is within the Biblo namespace. The code you are looking for is:
int main()
{
Biblo::Book book(100, 2012, "The Walrus", "The Eggman", Biblo::Book::Horror);
return 0;
}
You need to include the enum class. eg.:
Biblio::Book::Genre::Horror
Bunch of things that are going wrong really.
As others mentioned your enum is stashed one level deeper than you think it is, and your complaint about fixing it then producing an undefined reference is probably because at that point you bump into the fact there's nothing much initialized, and if you got past that you are returning items somewhat poorly when it comes to the enumerator.
If you use the right name space, quickly put in an actual implementation for the constructor, and get the most immediate return for your enum (an int might work) it should work, and probably look like this:
#include <iostream>
#include <string>
using namespace std;
namespace Biblo{
class Book{
public:
enum Genre{
No_Genre, Horror, Comedy, Romance, Mystery
};
// The rest of this header is working fine I think, just this enum
class Invalid{}; // Used for throwing errors
Book(int n_ISBN, int n_copyrightYear, string n_title, string n_author, Genre n_genre);
Book();
// Accessors (non-modifying)
int getISBN() const { return ISBN; }
int getCopyrightYear() const { return copyrightYear; }
string getTitle() const { return title; }
string getAuthor() const { return author; }
int getGenre() const { return genre; }
// Mutators
void changeAuthor(string newAuthor);
private:
int ISBN;
int copyrightYear;
string title;
string author;
Genre genre;
}; // End Book
Book::Book(int n_ISBN, int n_copyrightYear, string n_title, string n_author, Genre n_genre){
ISBN = n_ISBN; copyrightYear = n_copyrightYear; title = n_title; author = n_author;
};
}
using namespace std;
int main()
{
Biblo::Book book(100, 2012, "The Walrus", "The Eggman", Biblo::Book::Horror); // THIS LINE GIVES ERROR
cout << "ISBN: " << book.getISBN() << endl;
cout << "Copyright: " << book.getCopyrightYear() << endl;
cout << "Title: " << book.getTitle() << endl;
cout << "Author: " << book.getAuthor() << endl;
cout << "Genre: " << book.getGenre() << endl;
return 0;
}
Are you sue the book you're following isn't discussing details such as initializer lists or something else for constructors concurrent to, or previous to, the subjects you're looking at?
The code looked somewhat incomplete.
Edited in line here on SO, so bear with the poor formatting and the merged h/cpp look :)

Object doesn't listen to method or is not created? (C++ OO)

Whenever I try to make an object and call a function on it, it doesn't seem to work.
I have no idea why, since I don't seem to have errors too.
I have searched around on here regarding constructors and the toString-method, but haven't find anything that worked.
I have tried to edit (distinct) the members in the constructor members,
Tried to rewrite the toString method.
Tried to make local object (with no pointer).
But it doesn't return me the things in the object that I created when calling the constructor.
Where does the problem situate in this problem?
Here is my code:
.h file:
#pragma once
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
class Store{
private:
int id;
string name;
string adress;
string telephone;
string btwNumber;
public:
int getId();
void setId(int);
string getName();
void setName(string);
string getAdress();
void setAdress(string);
string getTelephone();
void setTelephone(string);
string getBtwNumber();
void setBtwNumber(std::string);
string toString();
Store(int, string, string , string, string);
};
.cpp file:
// Store.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Store.h"
Store::Store(int idnum, string nameS, string adreS, string telephonE, string btwnummeR){
idnum = id;
nameS = name;
adreS = adress;
telephonE = telephone;
btwnummeR = btwNumber;
}
int Store::getId()
{
return id;
}
void Store::setId(int id){
this->id = id;
}
string Store::getName(){
return naam;
}
void Store::setName(string name){
this->naam = naam;
}
string Store::getTelephone(){
return telephone;
}
void Store:setTelephone(string telephone){
this->telephone = telephone;
}
string Store::getBtwNumber()
{
return btwNumber;
}
void Store::setBtwNumber(string btwNumber){
btwNumber = btwNumber;
}
string Store::getAdress(){
return adress;
}
void Store::setAdress(string adress){
this->adress = adress;
}
string Store::toString(){
stringstream s;
s << "Id: " << id << endl;
s << "Naam: " << name << endl;
s << "Adres: " << adress << endl;
s << "Telefoonnummer: " << telephone << endl;
s << "BTWnummer: " << btwNumber << endl;
return s.str();
}
int _tmain(int argc, _TCHAR* argv[])
{
Store *test = new Store (4, "Test", "test", "test", "test");
test->toString();
system("Pause");
return 0;
}
Your constructor is inversed: you are assigning member variables to constructor arguments and not vice versa.
nameS = name;
Should be
name = nameS;
And so on
The method toString does work, but it won't magically decide to output its return value to screen. You'll have to do it yourself:
std::cout << test->toString() << std::endl;
You'll need to add #include <iostream> on top of your cpp file.

What is causing this Segmentation Fault: 11?

Okay, so this is effectively the first C++ I have ever written. Consequently, my attempts to research this Segmentation Fault error have failed to yield a useful response that I can understand. Most suggestions say that I'm exceeding the heap memory, but I don't see how I could be in this code. Maybe I'm trying to reference something that I can't reference?
Can someone please take a look at this code and possibly tell me what is causing this error? The code compiles fine, it just throws this error when it runs. I have tried commenting out all the code involving vectors, and that didn't solve the problem. I'm guessing it's something stupid that I'm missing or just a concept about C++ that I don't understand. Either way, some insight would be much appreciated! Thanks in advance.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
const int DEFAULT_SIZE = 15;
//---------------------------------User----------------------------------------------------------------------------------
//User Interface Definition
class User
{
public:
User(string nameValue);
string getName();
string getWall();
string getHome();
private:
string name;
};
//User Implementation Definition
User::User(string nameValue) : name(nameValue)
{
}
string User::getName()
{
return name;
}
//---------------------------------Group----------------------------------------------------------------------------------
//Group Interface Definition
class Group
{
public:
Group(string nameValue);
string getName();
void addMember(User newMember);
private:
string name;
vector<User> members;
};
//Group Implementation
Group::Group(string nameValue) : name(nameValue)
{
}
string Group::getName()
{
return name;
}
void Group::addMember(User newMember)
{
members.push_back(newMember);
}
//---------------------------------MessageBuffer----------------------------------------------------------------------------------
//MessgeBuffer Interface Declaration
class MessageBuffer
{
public:
MessageBuffer();
void insert(string user, string recipient, string message);
string readByGroup(string groupName);
string readByUser(string userName);
string readPublic();
private:
string buffer;
};
//MessageBuffer Implementation
MessageBuffer::MessageBuffer() : buffer("")
{
}
void MessageBuffer::insert(string user, string recipient, string message)
{
buffer = "|<" + user + "::" + recipient + ">|" + message + buffer;
}
string MessageBuffer::readByGroup(string groupName)
{
return "Something";
}
string MessageBuffer::readByUser(string userName)
{
return "Something";
}
string MessageBuffer::readPublic()
{
return "Something";
}
//---------------------------------System-------------------------------------------------------------------------------
//System Interface Definition
class System
{
public:
System();
void start();
private:
bool running;
User currentUser;
MessageBuffer messageBuffer;
vector<User> users;
vector<Group> groups;
};
//System Implementation Definition
System::System() : running(false), currentUser(0)
{
}
void System::start()
{
running = true;
string userSelection;
cout << "===========================================================" << endl;
cout << "|\t Welcome to the Auburn Messaging System! \t |" << endl;
cout << "===========================================================" << endl;
while (running) {
cout << "1) Create a new user\n";
cout << "2) Broadcast a message\n";
cout << "3) Multicast a message\n";
cout << "4) Unicast a message\n";
cout << "5) Display Wall page\n";
cout << "6) Display Home page\n";
cout << "7) Create a new group\n";
cout << "8) Join a group\n";
cout << "9) Switch to a different user\n";
cout << "10) Quit Auburn Messaging System\n";
cin >> userSelection;
if (userSelection == "1")
{
running = false;
}
}
}
//----------------------------------------------------------------------------------------------------------------------
int main() {
cout << "Part 1";
System system1;
cout << "Part 2";
system1.start();
cout << "Part 3";
return 0;
}
In the System constructor, currentUser(0) is attempting to initialise a the first parameter of the User constructor (a string) with a literal zero which will be interpreted as a null char pointer.
The std::string constructor (look for basic_string<char> in the debugger) which constructs a string from a char* will be called with a null pointer, which it will dereference and invoke undefined behaviour.

or C++: VS2010 multiplication operator being mistaken for a null pointer

I basically have exp>=level*10 in an else if expression, where level is a variable and 10 is a constant number. The code compiles completely fine without any errors, and it even worked after being compiled, until recently. now, whenever it compiles and executes, it gives me an error saying "invalid null pointer" and it conveniently tells me that the problem comes from the included file xstring (VS2010 includes it in new projects) on line 930.
Is there a way to force to program to read it as the multiplication operator instead of a null pointer?
EDIT: Here is my full code, please note that this is a protype created to ensure that it will work and was done prior to me realizing I can use derived classes for this. also note that I tried removing using namespace std to see if that was the problem.
#include "stdafx.h"
#include <iostream>
#include <sstream>
class player {
public:
std::string name;
int hp;
int attack;
int strength;
int defense;
void reward(int gold, int exp) {
player::gold += gold;
player::exp += exp;
player::levelHandler();
}
int dataQuery(std::string query) {
if (query == "equipment")
return helm, armour, greaves;
else if (query == "gold")
return gold;
else if (query == "exp")
return exp;
else if (query == "level")
return level;
else return 0;
}
private:
int helm;
int armour;
int greaves;
int level;
int gold;
int exp;
std::string levelHandler() {
if (level==0) {
level=1;
}
else if (exp>=(10*level)) { //causes problem due to * being mistaken as a
//null pointer.
int previousLevel = level;
level += 1;
levelHandler();
return 0;
};
return 0;
};
} hero;
class enemy {
public:
std::string name;
int hp;
int attack;
int strength;
int defense;
private:
int helm;
int armour;
int greaves;
int level;
int goldReward;
int expReward;
int dataQuery(std::string query) {
if (query == "equipment")
return helm, armour, greaves;
else if (query == "gold")
return goldReward;
else if (query == "exp")
return expReward;
else if (query == "level")
return level;
else return 0;
}
};
int main()
{
std::cout << "Please enter your character's name..." << std::endl;
std::cin >> hero.name;
std::cout << "Welcome to RPG Battle Simulation, " << hero.name << "!" << std::endl;
hero.reward(100, 0); //problem is either this line, or the function's call to levelHandler, as this is where the program terminates.
std::cout << "You are beginning your journey as a level " << hero.dataQuery("level") << " character." << std::endl;
std::cout << "Here is " << hero.dataQuery("gold") << " gold to get you started." << std::endl;
return 0;
};
The following is an excerpt of xstring that is causing the problem. the problem comes from _DEBUG_POINTER(_Ptr); (line 930)
_Myt& assign(const _Elem *_Ptr)
{// assign [_Ptr, <null>)
_DEBUG_POINTER(_Ptr);
return (assign(_Ptr, _Traits::length(_Ptr)));
}
This program reproduces your problem (when compiled with MSVC with runtime that supports debugging):
#include <string>
#include <iostream>
int main()
{
using namespace std;
string s = 0;
cout << s << endl;
}
The problem is that a std::string is initialized with a nullpointer.
EDIT: oh, forgot to mention, solution – simply don’t do that.
Cheers & hth.,