String not getting passed into class function - c++

class Message {
public:
void changeSubject(string);
string getSubject();
private:
string subject;
};
void Message::changeSubject (string subjecto) //change subject{
subject = subjecto;
}
string Message::getSubject () //return subject {
return subject;
}
int main ()
{
Message person;
string aboutwhat;
cout << "Enter subject" << endl;
getline(cin, aboutwhat);
person.changeSubject(aboutwhat);
cout << person.getSubject();
return 0;
}
Above isn't the full code. The problem right now is that it prints "Enter Subject" and ends the program. Why am I not prompted to cin?

Your code as posted has several issues and doesn't compile. The following works for me
// Include al necessary headers:
#include <iostream>
#include <string>
// Either qualify the namespace of `std::string`, `std::cin`, etc
// or place a using statement like follows
using namespace std;
class Message {
public:
void changeSubject(string);
string getSubject();
private:
string subject;
};
void Message::changeSubject (string subjecto) //change subject
{ // <<< You have hidden the opening brace after the comment above
subject = subjecto;
}
string Message::getSubject () //return subject
{ // <<< You have hidden the opening brace after the comment above
return subject;
}
int main ()
{
Message person;
string aboutwhat;
cout << "Enter subject" << endl;
getline(cin, aboutwhat);
person.changeSubject(aboutwhat);
cout << person.getSubject();
return 0;
}
See the working sample here please.
Since you have stated in your question, "This isn't the full code", I'd suspect you have some error in the other parts that weren't shown.
"Why am I not prompted to cin?"
One likely possibility is you have had other inputs on cin before, that were invalid and cin got into fail() state.
To prevent this, you can put a cin.clear(); statement before the getline() call.
If you take inputs like e.g. numbers, you should check for validity like this
int x;
do {
cout << "Enter a number please: "
if(cin >> x) {
break;
}
cout << "Not a valid number, try again." << endl;
cin.clear();
} while(true);

Since your code above looks correct.
I would suggest you first get the prompting working first.
Then add back more code later.
I just tested the following in my own environment
#include <iostream>
#include <string>
main ()
{
std::string aboutwhat;
std::cout << "Enter subject" << std::endl;
std::getline (std::cin,aboutwhat);
std::cout << "Subject: " << aboutwhat << std::endl;
return 0;
}

Related

First day at C++

I need to ask for the user's Initials and have it return their input. If they input any int I need it to loop back and ask them again.
int main()
{
// Program 1-1
std::cout<<"Hello, can you please enter your initials?\n";
char initials[50];
std::cin.getline(initials, 50);
while (std::cin != int)
{
std::cout << "Thank you. " << initials << std::endl;
}
else (std::cin.fail())
{
std::cin.clear();
}
}
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string tmp;
bool bogusInput;
do {
std::cout << "Initials: ";
std::getline(std::cin, tmp);
bogusInput = false;
for (auto i : tmp) {
if (std::isdigit(i)) {
bogusInput = true;
break;
}
}
if (bogusInput) {
std::cout << "Are you Elon's son? Please enter letters only.\n";
}
} while (bogusInput);
std::cout << "Thank you, " << tmp << ".\n";
return 0;
}
This code does the job you describe. I chose a do/while loop since I always need to get initials at least one time.
The variable bogusInput is a flag that I use to know if something hasn't worked out properly. It is declared outside of the loop for the sake of the while condition. It is always reset before performing the check, this allows the case of multiple attempts to work.
Finally, "valid" input gets us out of the loop and we say thank you and end.

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.

Function must return a value

I am trying to make a text based RPG and i'm fairly new to c++. I understand that I need to return a value, but when I try and return CharacterName or CharacterRace it comes up with unresolved externals errors. I'd really appreciate the help guys, thanks :)
CharacterCreation.h
#include <string>
#include <iostream>
void petc(), ConsoleClear(), petc(), EnterClear();
std::string CharacterName, CharacterRace;
Main.cpp
#include <iostream>
#include <limits>
#include <string>
#include <string.h>
#include "CharacterCreation.h"
std::string CharacterCreation();
int main()
{
CharacterCreation();
}
std::string CharacterCreation(int RaceChoice, int RaceChoiceLoop)
{
RaceChoiceLoop = 0;
std::cout << "Welcome to the character creation V 1.0.0" << std::endl;
EnterClear();
std::cout << "Choose a name: ";
std::cin >> CharacterName;
std::cout << CharacterName << std::endl;
EnterClear();
while (RaceChoiceLoop == 0)
{
std::cout << "(1) Human - Human's race perks: + 5 to Magic | + 1 to Sword Skill" << std::endl;
std::cout << "(2) Elf - Elve's race perks: + 5 to Archery | + 1 to Magic" << std::endl;
std::cout << "(3) Dwarf - Dwarven race perks: + 5 to Strength | + 1 to Archery" << std::endl;
std::cout << "Choose a race, " << CharacterName << ": ";
std::cin >> RaceChoice;
if (RaceChoice == 1)
{
RaceChoiceLoop = 1;
CharacterRace = "Human";
}
else if (RaceChoice == 2)
{
RaceChoiceLoop = 1;
CharacterRace = "Elf";
}
else if (RaceChoice == 3)
{
RaceChoiceLoop = 1;
CharacterRace = "Dwarf";
}
else
{
std::cout << "Invalid Option";
EnterClear();
RaceChoiceLoop = 0;
}
}
}
void petc()
{
std::cout << "Press Enter To Continue...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
void EnterClear()
{
std::cout << "Press Enter To Continue...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
system("cls");
}
void ConsoleClear()
{
system("cls");
}
A declared std::string function should return a string and this is not the same as printing it on the screen, use return "something" inside the function otherwise declare it void.
The "unresolved externals" message isn't directly caused by your returning a value.
It's a linker error, and only occurs because compilation succeeded.
The cause is that you're declaring, and calling, this parameter-less function:
std::string CharacterCreation();
but you're defining this function with two parameters:
std::string CharacterCreation(int RaceChoice, int RaceChoiceLoop)
The declaration and the definition must match.
From the looks of it, you don't actually want the parameters and should use local variables instead:
std::string CharacterCreation()
{
int RaceChoice = 0;
int RaceChoiceLoop = 0;
// ...
Problem is that the function CharacterCreation() (taking no arguments) is never defined, and thus the linker cannot find it.
Try substituting in the following:
std::string CharacterCreation(int, int);
int main()
{
CharacterCreation(1,1);
}
This will call the CharacterCreation function you have implemented below the main function. Doing this I can compile (and link) your code :)
As I have pointed in my comment before, your CharacterCreation method does not return any value, although you have defined a string as an expected one.
What you most likely want to do is either change CharacterCreation signature to:
void CharacterCreation(int RaceChoice, int RaceChoiceLoop)
and keep the current implementation
or pack all your console output in a string and return it at the end of the method.
Then in main()
string result = CharacterCreation();
can retrieve this value and you can print it in main

In C++, how do I ask the user to input a string, have that string stored, and be able to recall it in any/many functions?

I want to be able to have the user enter their name, store it and be able to recall it in different functions. This is my first code, first program. I am sure there is an easier way to do this, so if you could offer both an answer to the question and a easier way of accomplishing this task it would be much appreciated. Thank you in advance.
This is what I have so far:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
using namespace std;
void game();
void other();
class NameClass{
public:
string name;
};
int main()
{
int a;
int age;
string name;
cout << "Hello user, what is you name? \n\n";
/*Not sure if class and operator needs to be here. I was hoping that when the user
input the stream(their name) it would be stored in the class as well as being able
to use it in the main function.*/
NameClass person;
//This line is here to get name from user.
getline(cin, name);
cout << "Well " << name << ", are you having a good day? \n\n";
cout << "1=Yes 2=No \n\n";
cin >> a;
cout <<"\n";
if(a==1){
cout << "Well that is good to hear.\n\n";
}else{
cout << "I am sorry to hear that. I hope things get better for you. \n\n";
}
cout << "Do you want to play a game? \n\n";
cin >> a;
if(a==1){
game();
}else{
other();
return 0;
}
return 0;
}
void game(){
/*It is in this function that I want the be able to recall the name that the user input in the main function.*/
cout << "Cool "<< name <<",let get started." << endl;
}
void other(){
cout << "Well then "<< name <<", lets do something else.";
}
I assume you aren't aware of the OOP concepts.
Do this (make methods part of the class):
class NameClass{
public:
string name;
void game();
void other();
};
int main()
{
...
NameClass person;
getline(cin, person.name);
...
}
Or this (pass name as parameter):
int main()
{
string name;
...
game(name);
}
void game(string name)
{
cout << "Cool "<< name <<",let get started." << endl;
}
If you want to pass information from one function to another then you use a function parameter (or more than one).
void game(string name);
int main()
{
string name;
...
game(name);
}
void game(string name)
{
cout << "Cool "<< name <<",let get started." << endl;
}
It's a fundamental concept that pretty much all programming languages have.
Just pass the name as a parameter in both your functions, it should be something like this:
//functions
void game(string name);
void other(string name);
In your main function when you call either function just pass the name to it.
if(a == 1)
{
game(name);
}
else
{
other(name);
}

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.