How do I use the same string in 2 code blocks? - c++

just start C++ through a series of youtube tutorials, I tried to look online but I did not know what vocabulary to use to explain my problem. I was testing pointers and I made this file which basically gets a username from the user and says it again but I don't know how reuse the username in another codeblock.
// Testing Pointerds.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// This program just takes someones username and says it again.
// I get the name in void intro(), but how do I use the same string in another code block function?
// If I need to use it in 'void reuse()' how do I use the same name they type in in 'void intro()'?
void start()
{
cout << "What would you like to be called?"<<endl;
}
void usernameGet(string *a)
{
getline(cin,*a);
}
void intro()
{
string username;
start();
usernameGet(&username);
cout << "Welcome " << username << endl; // it has the username here but I want to use it in the next code block
cin.get();
}
void reuse()
{
// how do I use the same name in intro in this one?
}
int main()
{
intro();
reuse();
}

By passing the variable around, i.e. return it from the place where it's first initialized and pass it as an argument to the next place where it's needed. That way you avoid global state, which is nice.

You have to pass or return the value, something like:
std::string intro()
{
std::string username;
start();
usernameGet(&username);
std::cout << "Welcome " << username << std::endl;
std::cin.get();
return username;
}
void reuse(const std::string& name)
{
// Reuse name
}
int main()
{
std::string username = intro();
reuse(username);
}

Related

I'm trying to print from a void function, but it won't compile because it says it isn't defined [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My code won't compile, but I'm just trying to get my main file to run properly and print the output. I'm also trying to compare if the strings are equal to print. The main errors are in the main file because the header and cpp file compile, but when I try to get some output from the void print function, it crashes and tells me the errors that there's no matching function to call from the parent class. Can you please tell me how to fix this? thank you.
header file:
#include <iostream>
#ifndef BOOK_H
#define BOOK_H
class Book
{
public:
Book(std::string title, std::string author, int callNo);
virtual void print();
virtual bool equals(std::string book1, std::string book2);
protected:
std::string titleBook;
std::string auth;
int number;
};
class Journal: public Book
{
public:
Journal(int volume);
void print();
protected:
int vol;
};
#endif
cpp file
#include <iostream>
#include "Book.h"
using namespace std;
Book::Book(string title, string author, int callNo)
{
titleBook = title;
auth = author;
number = callNo;
};
void Book::print()
{
titleBook = " ";
auth = " ";
number = 0;
};
bool Book::equals(string book1, string book2)
{
bool printing = false;
if(book1 == book2) {
printing = true;
cout << "Books are a match!";
print();
}
else if (book2 != book1){
printing = false;
cout << "Books are not a match, try again.";
}
};
Journal::Journal(int volume):Book(titleBook, auth, number)
{
vol = volume;
};
void Journal::print()
{
vol = 0;
};
main file:
#include <iostream>
#include "Book.h"
using namespace std;
int main()
{
Book b1("Norton’s Star Atlas", "A.P. Norton", 510);
Book b2("Pocket Sky Atlas", "J. Sinot", 511);
if (b1.equals(b1, b2)) {
cout << "The books are the same" << endl;
}
else {
cout << "The books are different" << endl;
}
b1.print();
b2.print();
}
return 0;
}
Your issue is that your method signature and the actual call are different. In the method signature in the Book class, you have the signature written as:
virtual bool equals(std::string book1, std::string book2);
This tells the compiler that Book has a method named equals and takes a std::string and a std::string. But in the main function you call it using two books:
Book b1("Norton’s Star Atlas", "A.P. Norton", 510);
Book b2("Pocket Sky Atlas", "J. Sinot", 511);
b1.equals(b1, b2);
When the compile tries to find the equals method in Book, it does not find on which takes two Book instances rather than two std::string causing it to spit out the no matching function for call to ‘Book::equals(Book&, Book&)’ message.
You can fix this by adding an equals which accepts two Book instances. it should not matter whether you replace the existing function or overload the current one; however, I doubt that you would ever want to compare books by their string value rather than their actual member properties.
Your equal function declared to take two strings, but you have provided two Book objects.
Assuming you want to compare two titles in your Book, your function looks like this;
bool Book::equals(const Book& book1, const Book& book2)
{
if(book1.titleBook == book2.titleBook)
{
cout << "Books are a match!";
return true;
}
else
{
cout << "Books are not a match, try again.";
return false;
}
};
Your print functions doesn't make sense;
I have modified your print functions, to print object members;
void Book::print()
{
std::cout << "titleBook: " << titleBook << '\n'
<< "auth: " << auth << '\n'
<< "number: " << number;
};
void Journal::print()
{
std::cout << "vol: " << vol;
};

Getter seems to crash the program even with 0 errors

im new in the C++ world and coding in general, just started studying getters and setters and made areally simple exercise to practice them, the build seems to have 0 errors and 2 minor warnings, however, when I try to use a function to return a private variable and print it, it simply crashes the program, however, if i use the last function I made "getAccount()" It seems to work just fine.
After some poking, it seems like the problem is with the getter functions, just calling them crashes the program, here's the code:
main.cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
User user;
user.setUser("someuser");
user.setPassw("somepassword");
cout << user.getPassw() << endl;
cout << user.getUser() << endl;
user.getAccount();
}
Person.h
#define PERSON_H
#include <iostream>
using namespace std;
class User
{
private:
string username;
string password;
public:
string setUser(string usernm);
string setPassw(string pass);
string getUser();
string getPassw();
void getAccount();
};
#endif // PERSON_H
Person.cpp
#include <iostream>
#include "Person.h"
using namespace std;
string User::setUser(string usernm){
usernm = username;
}
string User::setPassw(string pass){
pass = password;
}
string User::getUser(){
return username;
}
string User::getPassw(){
return password;
}
void User::getAccount(){
cout << "Account is:" << endl;
cout << "Username: " + username << endl;
cout << "Password: " + password << endl;
}
Not all functions declared to return values actually return values so you have Undefined Behaviour and anything could happen.
Example:
string User::setUser(string usernm){
usernm = username;
// should return a string here
}
string User::setPassw(string pass){
pass = password;
// should return a string here
}
Apart from that, you assign usernm and pass when you should assign username and password so the set operations does not set the member variables.

Calling a string getter function from a header file

I'm learning C++, and I'm just messing around with putting classes in separate files for practice. I have a getter function, which returns a string (because the variable is saved as a string). However, from my main() function, I am not sure how to call it. I know the problem is probably that I need to include string somewhere when I call the object, but I have no idea how to format it.
I know this is a pretty newbie questions, but I couldn't find the answer anywhere. Could someone help me out?
(p.s. I'm not trying to get this specific code to work, since it's useless. I'm just trying to learn how to apply it for future reference).
I've tried throwing in string in a couple of places when calling or creating the object, but I always get an error. I know I could get around it by not encapsulating the variable or not having a separate class file, but that's not what I want.
main.cpp
#include <iostream>
#include "usernameclass.h"
#include <string>
using namespace std;
int main()
{
usernameclass usernameobject;
usernameobject.getUsername();
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
usernameclass();
std::string getUsername();
void setUsername(std::string name);
askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include "usernameclass.h"
#include <iostream>
#include "username.h"
#include <string>
using namespace std;
string usernameclass::getUsername(){
return usernameVar;
cout << "test cout" << endl;
}
usernameclass::askUsername(){
string name;
cout << "What is your name?" << endl;
cin >> name;
setUsername(name);
cout << "Ah, so your name is "+usernameVar+", great name I guess!" << endl;
cin.get();
cin.get();
cout << "You're about to do some stuff, so get ready!" << endl;
}
usernameclass::usernameclass(){}
void usernameclass::setUsername(string name){
string* nameptr = &usernameVar;
*nameptr = name;
}
Expected result: runs getUsername() function and returns usernameVar
Actual result: doesn't run the getUsername() function
The current code would not compile, because you have not specified return type of 'askUsername()' routine, which is 'void', I believe.
Other things are good, apart from an output in 'getUsername()', which happens after returning from the function and about which you should have received a warning, I guess.
To the question: you can call that 'get' method in 'main()' as:
cout << usernameobject.getUsername();
Your code should be structured more like this instead:
main.cpp
#include <iostream>
#include "usernameclass.h"
int main()
{
usernameclass usernameobject;
// optional:
// usernameobject.askUsername();
// do something with usernameobject.getUsername() as needed...
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
std::string getUsername() const;
void setUsername(std::string name);
void askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include <iostream>
#include "usernameclass.h"
std::string usernameclass::getUsername() const {
return usernameVar;
}
void usernameclass::setUsername(std::string name) {
usernameVar = name;
}
void usernameclass::askUsername() {
std::string name;
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, std::name);
setUsername(name);
std::cout << "Ah, so your name is " << getUsername() << ", great name I guess!" << std::endl;
std::cout << "You're about to do some stuff, so get ready!" << std::endl;
}

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);
}

Understanding Data Structures and Classes C++

So I'm having trouble understanding how Struct works in C++ I have develop a code in which I've been playing for a while but I don't seem to display for the results I'm looking for. I don't get any compiler errors or mistakes so it seems to be running ,This is what I have ...
Question: How do I display the results in "void Save_Player_Name(Player_Data Player)" later on in the future... ?
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
int main()
{
Save_Name_File();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << string(30, '\n');
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
}
}
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}
Edit: minor fixes.
Edit: Added class consideration.
Question: How do I display the results in "void
Save_Player_Name(Player_Data Player)" later on in the future... ?
If you are asking how to read the data in from a file:
const bool readFile()
{
ifstream ip;
ip.open("scores.dat", ifstream::in);
if( !ip )
{
printf("Unable to open file.");
return false;
}
// loop over every line in the file
string bffr;
while( getline(ip, bffr) )
{
<do something>
}
}
If you are referring to how to access the data stored in the variable:
Technically, you should be able to do the following from main:
Save_NameFile();
printf("Player name: %s", Customer[n].Player_name.c_str());
However, having Customer be global is bad for a number of reasons. Instead, you should create a local instance in main and pass it to your functions. You will then be able to access it in the same manner.
Note: I used printf instead of cout. I would recommend getting familiar with it. You'll need to include stdio.h, I believe.
Also, you need to make sure you are passing your struct by reference. There are a number of reasons why you should do this, but you will need to in order to get the data back out.
void Save_Player_Name(Player_Data &Player) {<<stuff here>>}
You should also be declaring your functions before main:
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
};
void askUserForName(Player_Data &);
void writeNameToFile(Player_Data &);
void main()
{
Player_Data player;
askUserForName(player);
return;
}
void askUserForName(Player_Data &player)
{
<<do stuff>>
writeNameToFile(player);
return;
}
etc.
Unless you really need to use a struct, I would recommend going with classes. Structs make everything (variables and methods) public by default, whereas classes are private by default. In reality, structs and classes are identical--you can use them fairly interchangeably (don't shoot me!); in practice, structs are generally used when you need to aggregate some data (i.e., variables) without methods.
Your class might end up something like this (I haven't tested it, and I've been coding in Python lately, so please forgive any minor errors):
class PlayerData
{
public:
PlayerData()
{
}
~PlayerData()
{
}
void askUserForName()
{
<<code here>>
}
void writeNameToFile()
{
<<code here>>
// also write to screen
printf("[Write to console] name: %s\n", this->name_.c_str());
}
private:
std::string name_;
};
void main()
{
PlayerData player;
player.askUserForName();
player.writeNametoFile();
return;
}
In reality, you'd want to use a header file and separate things out, but I'll leave that for another day.
You haven't called the method that saves the player after you call Save_Name_File()
You need some logic fixes for your code
#include <iostream>
#include <fstream>
using namespace std;
struct Player_Data
{
public: string Player_Name;// name of the player will be store here
}Customer[1];
void Save_Player_Name(Player_Data Player)// will store the name of the player in a file
{
ofstream scores_data;
scores_data.open ("scores.dat", std::ios_base::app);
cout << Player.Player_Name << endl;
scores_data<< Player.Player_Name << "\n";
scores_data.close();
}
void Save_Name_File()// will capture the name of the player
{
int n;
int i = 1;// number of players
//cin.get();
for (n=0; n<i; n++)// will the player
{
cout << "Player Amount " << n << " Out of : " << i;
cout << "\n Please enter the name you wish to play \n\n Name: ";
getline (cin,Customer[n].Player_Name);
Save_Player_Name(Customer[n]);
}
}
int main()
{
Save_Name_File();
return 0;
}