How can I use a string from another function? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my program ( I will include code below ), I have a function to determine the user's name and height. I use the name function first void name() and then the function void height() following it (of course main is last).
What I'm trying to do is to display the user's name throughout the program. In my second function, void height() Is ask the user how tall they are:
cout << " How tall are you?" << endl;
I would like to ask " How tall are you, name1?" , but the string name1 is not declared in the scope. Any ideas of how to make it work / what I'm doing wrong? Thank you. Also if you see any other issues or something I can do to make things easier/alternative ways, please let me know! (I'm new!)
#include <iostream>
#include <string>
using namespace std;
void name()
{
cout << "Welcome ________ ... uhmmmm, what was your name again? ";
string name1;
cin >> name1;
cout << " " << endl;
cout << " Oh that's right! Your name was " << name1 << ", how could I forget that?!" << endl;
}
void height()
{
//feet and inches to inches
cout << " How tall are you?" << name1 << endl;
cout << " " << endl;
cout << " " << endl;
cout << " Enter feet: ";
int feet;
cin >> feet;
cout << " " << endl;
cout << " Enter inches: ";
int inches;
cin >> inches;
int inchesheight;
inchesheight = (feet * 12) + inches;
cout << " " << endl;
cout << " Your height is equal to " << inchesheight << " inches total." << endl;
if (inchesheight < 65 )
{
cout << " You are shorter than the average male." << endl;
}
else if (inchesheight > 66 && inchesheight < 72)
{
cout << " You are of average height." << endl;
}
else
{
cout << " You are taller than average." << endl;
}
}
int main()
{
name();
height();
return 0;
}

Return a string instead of void.
string name()
{
cout << "Welcome ________ ... uhmmmm, what was your name again? ";
string name1;
cin >> name1;
cout << " " << endl;
cout << " Oh that's right! Your name was " << name1 << ", how could I forget that?!" << endl;
return name1;
}
Same thing with height(), for example, that should return an int. Also to get the name in your height function you could do.
int height(string name1)
{
// cout stuff about name
return userHeight;
}
Then you can call it like this:
int main()
{
string userName = name(); // takes the return from name and assigns to userName
int userHeight = height(userName); // passes that string into height()
return 0;
}
More examples of using functions and returning things:
int add(int a, int b)
{
int total = a + b; // the variable total only exists in here
return total;
}
int add4Numbers(int w, int x, int y, int z)
{
int firstTwo = add(w, x); // I am caling the add function
int secondTwo = add(y,z); // Calling it again, with different inputs
int allFour = add(firstTwo, secondTwo); // Calling it with new inputs
return allFour;
} // As soon as I leave this function, firstTwo, secondTwo, and allFour no longer exist
// but the answer allFour will be returned to whoever calls this function
int main()
{
int userA = 1;
int userB = 7;
int userC = 3;
int userD = 2;
int answer = add4Numbers( userA, userB, userC, userD ) // this grabs the value from allFour from inside the add4Numbers function and assigns it to my new variable answer
return answer; // now equals 13
}

Related

C++ Passing a variable to another function

int samuelt1(){
ela = 80;
socials = 80;
total = ela + socials;
int grade = total / 11.5;
cout << "Samuel's grade average for term 1 is: " << grade << "%" << endl;
cout << "Individual Subjects: " << endl;
cout << "ELA: " << ela << endl;
cout << "Socials: " << socials << endl;
return grade;
}
int average(){
int avg = [samuelt1's grade??] / 1;
cout << avg;
return 0;
}
I'd like to pass the grade variable over to the average function; is there a way to do that? Thanks!
In the main function, store the value returned by the function samuelt1 in the variable Grade. Pass Grade as a parameter to the function average, like so
#include <iostream>
using namespace std;
int samuelt1(){
int ela = 80;
int socials = 80;
int total = ela + socials;
int grade = total / 11.5;
cout << "Samuel's grade average for term 1 is : " << grade << "%" << endl;
cout << "Individual Subjects : " << endl;
cout << "ELA : " << ela << endl;
cout << "Socials : " << socials << endl;
return grade;
}
int average(int grade){
int avg = grade / 1;
cout << "Average : " << avg;
return 0;
}
int main(){
int Grade = samuelt1();
average(Grade);
}
In C++, as in most languages, functions can be created to accept parameters and/or return values. To do this, you just need to specify a type and a name inside the parenthesis. Here is an example:
void printGrade(int grade)
{
cout << grade << endl;
}
int main()
{
int grade = 10;
printGrade(grade);
}
Running that program will print 10 to the screen. One thing to note is that when you pass in an integer parameter, the computer is just creating a copy of the value. This means the original grade variable is not changed or affected. Consider this example:
void printGrade(int grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You may expect this program to print 10, followed by 15. Since a copy of value is created inside the printGrade() function, the value of grade is affected only inside the scope of the printGrade() function. If you need to change the original value inside the printGrade() function, then you must pass the parameters by reference. Here is an example:
void printGrade(int &grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You'll notice in this example, the variable name is preceded with an ampersand. This tells the computer that you want to pass a reference to the grade variable to the function rather than making a copy.
Hopefully this all makes sense!

"invalid operands to binary expression" in simple class using memory and addresses

#include <iostream>
using namespace std;
class Animal
{
public:
string eat()
{
return "I can Eat";
}
string sleep()
{
return "I can sleep";
}
void showData(int *weight, int *age)
{
cout << "The weight is " << weight << " and the age is " << age << endl;
}
};
int main()
{
Animal an;
int x;
int y;
cout << "Enter the height and weight of the dog." <<endl;
cin >> x;
cin >> y;
cout << an.eat()<< endl;
cout << an.sleep()<<endl;
cout << an.showData(&x,&y) << endl;
return 0;
}
At the part that states:
cout << an.showData(&x,&y)
I get an error stating:
invalid operands to binary expression
I thought that by using addresses, I can instantly be able to output the function, but apparently I guess there is some incompatibility?
showData() returns void, ie nothing. So there is nothing to pass to operator<<, hence the error.
Simply change cout << an.showData(...) to an.showData(...), since showData() does its own cout statements internally.
If you want cout << an.showData(...) to actually display something, then showData() needs to return something worth displaying, such as a std::string, eg:
string showData(int *weight, int *age)
{
return "The weight is " + to_string(*weight) + " and the age is " + to_string(*age);
}
Animal an;
cout << an.showData(&x,&y) << endl;

How to make void not return when answer == true [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I made this program and when I type "yes" it should end my program instead it's waiting for me to say something more and then it comes with my void nottrue(); what should I do to avoid this? Here's my code
#include <iostream>
using namespace std;
void CharacterWorld();
void nottrue();
int main()
{
CharacterWorld();
nottrue();
return 0;
}
void CharacterWorld()
{
string CharacterName;
int CharacterAge;
string yesorno;
cout << " Hi, welcome to the Vanish World! " << endl;
cout << " What's your name champion? " << endl;
cin >> CharacterName;
cout << " ...And what's your age? " << endl;
cin >> CharacterAge;
cout << " ... So your name is " << CharacterName << " and your age is " << CharacterAge << " Is that right?" << endl;
cin >> yesorno;
if (yesorno == "yes")
{
cout << " Okey! so let's start your journey champion!" << endl;
}
else
{
cout << " SO what's your name then ??" << endl;
return nottrue();
}
}
void nottrue()
{
string CharacterName;
int CharacterAge;
string yesorno;
cin >> CharacterName;
cout << " and what's your age?" << endl;
cin >> CharacterAge;
cout << " ...Okey, already. Your name is " << CharacterName << " and your age is " << CharacterAge << endl;
}
While return nottrue() works , it's nothing but a function call, because both caller and called function have no returned value. You don't alter flow in any way.
You have to use results returned by function for control flow. E.g.
bool CharacterWorld()
{
//...
if (yesorno == "yes")
{
cout << " Okey! so let's start your journey champion!" << endl;
return true;
}
else
{
cout << " SO what's your name then ??" << endl;
return false;
}
}
int main()
{
if(!CharacterWorld())
nottrue();
return 0;
}
Also there is predefined exit() function to exit program.

C++ class loop in main

I need help in a simple way of solving a part of my code that i cant seem to make it work.The point of my "assignment" is that everything must try to be in one class.Now the problem i am having is at a part of my code where it is suppose to "print" the n number of products meaning that it displays what you have inputted in the void get() part,but the problem i cant seem to resolve is it only prints the last name,amount,weight of the product and not everything written.
class Class
{
public:
string name;
int n, amount;
float weight;
void market()
{
cout << "Give the number of products you want to get at Market : " << endl;
cin >> n;
}
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name >> amount >> weight;
}
}
void print()
{
cout << "\nProduct display:\n" << endl;
for (int i = 0; i < n; i++)
{
cout << name << " - " << amount << " , " << weight << " kg" << endl;
cout << "------------------------" << endl;
}
};
};
The main part.
int main()
{
Class market;
market.market();
market.get();
market.print();
}
You're actually overwriting name, amount and weight. You have to make use of something similar to std::vector:
class Class {
public:
std::vector<string> names;
// Same for others
When you get them from std::cin you have to push them into the vector:
names.push_back(name);
amounts.push_back(amount);
weights.push_back(weight);
When printing you loop over the vectors:
for (int i = 0; i < n; i++) {
cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
cout << "------------------------" << endl;
}
You must use a std::vector<TYPE> (example 1), or array for holding multiple data in a single variable (example 2).
Example 1
Since you've been coding in C++ programming language, it's highly recommended to use std::vector<> for best results.
Consider the class example (read comments too):
int count = 0; // PRIVATE SECTION
char ask;
std::vector<std::string> name;
std::vector<int> amount;
std::vector<float> weight;
std::string tName; // temp variables
int tAmount;
float tWeight;
public:
void market()
{
cout << "WELCOME!" << endl; // nothing's required with vector
}
void get()
{
do {
cout << "Give product name, amount and weight : " << endl;
cin >> tName >> tAmount >> tWeight; // getting temporary variables
name.push_back(tName); // assigning
amount.push_back(tAmount);
weight.push_back(tWeight);
count++;
cout << "Add more? (Y/n): "; // add more? Go on if yes...
cin >> ask;
} while (ask == 'Y' || ask == 'y');
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < count; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
WELCOME!
Give product name, amount and weight :
ABC 12 55.5
Add more? (Y/n): y
Give product name, amount and weight :
SSD 33 43.2
Add more? (Y/n): n
Product display:
ABC - 12 , 55.5 kg
------------------------
SSD - 33 , 43.2 kg
------------------------
Example 2
You can do the same thing just with few modifications, but having static number isn't considered dynamic. You can use arrays for your program as stated below.
Rather than:
string name;
int n, amount;
float weight;
Consider const int MAX = 1024; and use (class variables must be visible only inner the class and nowhere else):
private: // declare on top of the class ("private:" is by default and redundant)
string name[MAX];
int n, amount[MAX];
float weight[MAX];
Edited & working example class:
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name[i] >> amount[i] >> weight[i];
}
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < n; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
Give the number of products you want to get at Market :
2
Give product name,amount and weight :
ABC 25 102
Give product name,amount and weight :
BDE 22 333
Product display:
ABC - 25 , 102 kg
------------------------
BDE - 22 , 333 kg
------------------------

How to use struct members in a struct's member function?

So the purpose of the program is to Create an array of 3 people, allow the user to populate the data in a for loop, ensure that the results are capitalized, and output the results.
These new projects instructions were to
1. Rewrite capitalize() as a method within the structure.
2. Rewrite printPerson() as a method within the structure
The program itself works just fine, it's just not in the format that my professor wanted. He said the point of it is to not use any arguments but again, I don't know what he means. I just started programming a few months ago and even though I'm trying I don't have a strong knowledge of the terminology.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
string firstName;
string middleName;
string lastName;
int age;
string gender;
void capitalize(Person &arg);
void printPerson(Person arg);
};
Pretty sure these are the methods right here, but I'm not sure if the (person &arg) and (person arg) are the arguments itself or if they are parameters. I thought it was the "arg" part but I can't find a way to get the program to run without them as I'm pretty sure I need the & of operator to modify the information.
int main(void) {
Person myPerson;
Person a[3];
const int size = 5;
for (int i = 0; i <= 2; i++) {
cout << "What is First Name #" << i + 1 << "? ";
getline(cin, a[i].firstName);
cout << "What is Middle Name #" << i + 1 << "? ";
getline(cin, a[i].middleName);
cout << "What is Last Name #" << i + 1 << "? ";
getline(cin, a[i].lastName);
cout << "Age #" << i + 1 << "? ";
cin >> a[i].age;
cin.ignore();
cout << "Male or Female #" << i + 1 << "? ";
getline(cin, a[i].gender);
cout << endl;
}
for (int i = 0; i <= 2; i++) {
myPerson.capitalize(a[i]);
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
myPerson.printPerson(a[i]);
}
system("pause");
return 0;
}
Along with that, I don't know how to manipulate the functions to work without the "parameters/arguments" (I'm not sure the difference at this point) or without the "arg"
void Person::capitalize(Person &arg) {
transform(arg.firstName.begin(), arg.firstName.end(), arg.firstName.begin(), ::toupper);
transform(arg.middleName.begin(), arg.middleName.end(), arg.middleName.begin(), ::toupper);
transform(arg.lastName.begin(), arg.lastName.end(), arg.lastName.begin(), ::toupper);
}
void Person::printPerson(Person arg) {
cout << "\nFirst Name: " << arg.firstName << endl;
cout << "\nMiddle Name: " << arg.middleName << endl;
cout << "\nLast Name: " << arg.lastName << endl;
cout << "\nAge: " << arg.age << endl;
cout << "\nGender: " << arg.gender << endl;
cout << "\n\n";
}
The capitalize and the printPerson are now members (usually called methods) of the struct Person. This means that they operate on the member variables of an Person instance. Like this, you can just access all the classes members in these methods. See the following code. I also completed it with a constructor and made it slightly more readable.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
public:
Person();
void readFromUserInput();
void capitalize();
void print();
public:
string firstName;
string middleName;
string lastName;
int age;
string gender;
};
Person::Person() :
firstName(""),
middleName(""),
lastName(""),
age(0),
gender("")
{
}
void Person::readFromUserInput()
{
cout << "What is the First Name ? ";
getline(cin, firstName);
cout << "What is Middle Name ? ";
getline(cin, middleName);
cout << "What is Last Name ? ";
getline(cin, lastName);
cout << "Age ? ";
cin >> age;
cin.ignore();
cout << "Male or Female ? ";
getline(cin, gender);
}
void Person::capitalize()
{
transform(firstName.begin(), firstName.end(), firstName.begin(), ::toupper);
transform(middleName.begin(), middleName.end(), middleName.begin(), ::toupper);
transform(lastName.begin(), lastName.end(), lastName.begin(), ::toupper);
}
void Person::print()
{
cout << "\nFirst Name: " << firstName << endl;
cout << "\nMiddle Name: " << middleName << endl;
cout << "\nLast Name: " << lastName << endl;
cout << "\nAge: " << age << endl;
cout << "\nGender: " << gender << endl;
cout << "\n\n";
}
int main(void)
{
const int NUM_PERSONS = 3;
Person a[NUM_PERSONS];
for (int i = 0; i < NUM_PERSONS; i++)
{
cout << "### " << (i + 1) << ". User:" << endl;
a[i].readFromUserInput();
cout << endl;
}
for (int i = 0; i < NUM_PERSONS; i++)
{
a[i].capitalize();
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
a[i].print();
}
system("pause");
return 0;
}