C++ Return Statement Not Working - c++

I've just started learning C++ and i've been having problems implementing return statements. I've been easily able to pass data to a new function but I am having no joy in getting it to return.
I've written the simplest code I could think of to try and debug what is going wrong and I still can't work it out. I am NOT trying to pass too many return values and I have a correct function type to pass too. It just doesn't seem to work?
I am using Xcode 4 on a Macbook Pro:
#include <iostream>
using namespace std;
int agenext (int age);
int main ()
{ int age;
cout << "What's Your Age? \n";
cin >> age;
cout << "Your Current Age: " << age;
agenext(age);
cout << endl << "A year has passed your new age is: ";
cout << age;
}
int agenext (int x)
{
x++;
cout << endl << "Your Next Birthday is " << x;
return x;
}

It's returning perfectly find. You just aren't setting the value it returns to anything.
age = agenext(age)
Is what you are looking for, or you could pass a pointer or a reference to the age variable.

returning is only half the battle, the other half is assigning that value to something. Consider changing:
agenext(age);
to
age = agenext(age);

Both the existing answers are correct; if you want to return a value, it needs to be assigned somewhere.
For future reference, you can also do what you want by skipping the return and passing age by reference instead of value.
void agenext (int &x)
{
x++;
cout << endl << "Your Next Birthday is " << x;
/* the value change WILL show up in the calling function */
}

In your main function, you need another variable to hold the new age that is return from the age function.
int main ()
{ int age, newAge;
cout << "What's Your Age? \n";
cin >> age;
cout << "Your Current Age: " << age;
newAge = agenext(age);
cout << endl << "A year has passed your new age is: ";
cout << newAge;
return 0;
}

Related

i made c++ code where its need to pass structure pointer in a function

i got confused about the structure when i need to to pass the value in a function
#include <iostream>
using namespace std;
struct student
{
int studentID;
char studentName[30];
char nickname[10];
};
void read_student(struct student *);
void display_student(struct student *);
int main()
{
student *s;
//struct student *ps;
read_student(s);
display_student(s);
}
void read_student(struct student *ps)
{
int i;
for (i = 0; i <= 2; i++)
{
cout << "Enter the studentID : ";
cin >> ps->studentID;
cout << "Enter the full name :";
cin.ignore();
cin >> ps->studentName;
cout << "Enter the nickname : ";
cin.ignore();
cin >> ps->nickname;
cout << endl;
}
}
void display_student(struct student *ps)
{
int i;
cout << "student details :" << endl;
for (i = 0; i <= 2; i++)
{
cout << "student name : " << *ps ->studentName << " (" << &ps ->studentID << ")" << endl;
ps++;
}
}
its only problem at the variable at line 19 and when i try to edit it will became more problem
student *s;
//struct student *ps;
//struct student *ps;
read_student(s);
display_student(s);
also can someone explain how to transfer pointer value of structure to the function and return it back to the main function
You are suffering from some leftovers from your C-Language time. And, you have still not understood, how pointer work.
A pointer (as its name says) points to something. In your main, you define a student pointer. But it is not initialized. It points to somewhere. If you read data from somewhere, then it is undefined behavior. For writing, it is the same, plus that the system will most likely crash.
So, define a student. And if you want to give it to a sub-function, take its address with th &-operator (this address will point to the student) and then it will work.
You need also to learn abaout dereferencing. Your output statement is wrong.
Last but not least, if you want to store 3 students, then you need an array or some other storage where to put them . . .
In your read function you always overwrite the previously read student and in your display function you show undetermined data.
Please have a look at your minimal corrected code:
#include <iostream>
using namespace std;
struct student
{
int studentID;
char studentName[30];
char nickname[10];
};
void read_student( student*);
void display_student( student*);
int main()
{
student s;
//struct student *ps;
read_student(&s);
display_student(&s);
}
void read_student( student* ps)
{
cout << "Enter the studentID : ";
cin >> ps->studentID;
cout << "Enter the full name :";
cin.ignore();
cin >> ps->studentName;
cout << "Enter the nickname : ";
cin.ignore();
cin >> ps->nickname;
cout << endl;
}
void display_student( student* ps)
{
cout << "student details :" << endl;
cout << "student name : " << ps->studentName << " (" << ps->studentID << ")" << endl;
ps++;
}
And, the commenters are right. You must read a book.

How to multiply/divide one function to another ? How to use parameters?

How do I multiply a function to another function? and how do I properly use parameters?
I'm not exactly sure, I am really new to C++ with only about 14 weeks of class time.
Something I've tried would be creating a new function meant to multiply other functions and in the arguments I would put in the functions names.
For example:
float mealMath(numberOfAdults, mealChoosing){
//Rest of function
}
but I always get an error.Please explain how to fix this, this is a big obstacle in programming for me and I can't seem to grasp how to fix this or go about doing these things. Don't be to harsh on me for this.Thanks!
int numberOfAdults(){
int totalAdults;
cout << "Now how many adults will there be?: ";
cin >> totalAdults;
cout << "It seems there will be: " << totalAdults << " Adults." << endl;
while(totalAdults < 1){
cout << "Sorry there has to be a minimum of 1 adult!" << endl;
cout << "How many adults: ";
cin >> totalAdults;
}
return 0;
}
int numberOfKids(){
int totalKids;
cout << "Now how many Kids will there be?: ";
cin >> totalKids;
cout << "It seems there will be: " << totalKids << " kids." << endl;
while(totalKids < 0){
cout << "Sorry there has to be a minimum of 1 Kid!" << endl;
cout << "How many Kids: ";
cin >> totalKids;
}
return 0;
}
float mealChoosing(){
float cost;
string mealChoise;
cout << " " << endl;
cout << "Now, What meal will you be getting(D/S): ";
cin >> mealChoise;
if(mealChoise == "D"){
cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
cost = 25.95;
}
if(mealChoise == "S"){
cout << "It seems you have selected the Standard Meal plan for everyone!" << endl;
cost = 21.75;
}
cout << " " << endl;
return cost;
}
One expected result is I want to multiply the input that the user gives in function "numberOfAdults" to the input a user gives for "mealChoosing"
So I want numberOfAdults * mealChoosing but I want that done in a different function so
"float total(){
float totalBill;
totalBill = numberOfAdults * mealChoosing;
cout << totalBill;"
or something along those lines. I can't complete this project because I can't for some reason properly give the functions the proper information needed in parameters.
In this case(and most) you should not declare a function whose parameters are functions. Instead declare mealMath with an integer and a float input:
float mealMath(int a, float b){/*Your code here*/}
And then later call mealMath with the other two functions passed as arguments.
float x = mealMath(numberOfAdults(), mealChoosing());
Alternatively you can have no function parameters for mealMath() and instead call numberOfAdults() and mealChoosing() from inside of the function.
It's important to note that most of the time you'll be calling a function and using its output as an argument, and therefore you'll need to put the () after the function's identifier, instead of just typing the identifier alone.
Like mealChoosing() return totalAdults and totalKids (although its not needed here) from numberOfAdults(), numberOfKids() respectively.
int numberOfAdults() {
//...
return totalAdults;
}
int numberOfKids() {
//..
return totalKids;
}
float mealChoosing() {
//..
return cost;
}
Now on mealMath(numberOfAdults, mealChoosing)
float mealMathOutput = mealMath(numberOfAdults(), mealChoosing());

How to Create & Add new object in existing array using Dynamic Memory allocation

I am trying to do some stuff with C++ and i am new in it :)
I have tried 1 program of class that gets the student details and print the output of it.
#include <iostream>
using namespace std;
#define MAX 10
class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};
//member function definition, outside of the class
void student::getDetails(void){
cout << "Enter name: " ;
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;
perc=(float)total/500*100;
}
//member function definition, outside of the class
void student::putDetails(void) {
cout << "Student details:\n";
cout << "Name:"<< name << ",Roll Number:" << rollNo << ",Total:" << total << ",Percentage:" << perc;
}
int main()
{
student std[MAX]; //array of objects creation
int n,loop;
cout << "Enter total number of students: ";
cin >> n;
for(loop=0;loop< n; loop++){
cout << "Enter details of student " << loop+1 << ":\n";
std[loop].getDetails();
}
cout << endl;
for(loop=0;loop< n; loop++) {
cout << "Details of student " << (loop+1) << ":\n";
std[loop].putDetails();
}
return 0;
}
Its very basic code and works fine and I am able to give inputs and print the output.
Now I want to add new Student object at runtime using Dynamic memory allocation and want to add that object in the existing array of object (So that I can get the highest, lowest marks of any student)
I know I need to use new operator for this.
But I am not sure what could be the best way to write this solution.
Any help will be highly appreciated.
Thanks!
IMO, The best way to do this using dynamic memory is by using std::unique_ptr or std::shared_ptr (it actually depends on the requirement).
Here is one example of usage of unique_ptr:
using StudentPtr = std::unique_ptr<student>;
int main() {
std::vector<StudentPtr> studentDetails;
int n;
cout << "Enter the number of students: ";
cin >> n;
studentDetails.resize(n);
for (auto &s: studentDetails) {
s = StudentPtr(new student);
s->getDetails();
}
return 0;
}
For getting minimum and maximum, you may use min_element and max_element provided by STL respectively.

C++ having input to class

I made 2 function : getdata, print for input/print variable in person class
#include <iostream>
#include <string>
using namespace std;
class person {
public:
char name[19];
int born_year, married_year;
};
void getdata(char* name, int born_year,int married_year) {
cout << "Enter Name!\n > ";
cin.getline(name, 19);
cout << "What's the Born Year?\n > ";
cin >> born_year;
cout << "What's the Married Year?\n > ";
cin >> married_year;
}
void print(char* name, int born_year, int married_year) {
cout << "Your Name : " << *name;
cout << "\n Your Born Year : " << born_year;
cout << "\n Your Married Year : " << married_year;
}
int main(void) {
person p;
int born_year, married_year;
getdata(p.name, p.born_year, married_year);
print(p.name, p.born_year, p.married_year);
return 0;
}
I'm trying to have input in a function outside the class
(class only have variables about person)
and print with with other function.
How could I make this work?
Your problem is in the variable types to your getdata function. The integer parameters need to be pass-by-reference (either pointers or references, the latter being preferred). Right now you pass in a copy of the born_year and married_year values. When you get the input you save that into local variables; the passed parameters are never updated.
You want something like this:
void getdata(char* name, int &born_year,int &married_year)
With that tiny change (adding the two & characters) your code should work as you expect.
#include <iostream>
#include <string>
using namespace std;
class person {
public:
char name[19];
int born_year, married_year;
};
void getdata(char* name, int &born_year, int &married_year) {
cout << "Enter Name!\n > ";
cin.getline(name, 19);
cout << "What's the Born Year?\n > ";
cin >> born_year;
cout << "What's the Married Year?\n > ";
cin >> married_year;
}
void print(char* name, int born_year, int married_year) {
cout << "Your Name : " << name;
cout << "\n Your Born Year : " << born_year;
cout << "\n Your Married Year : " << married_year;
}
int main(void) {
person p;
getdata(p.name, p.born_year, p.married_year);
print(p.name, p.born_year, p.married_year);
return 0;
}
If you want passed variables to be changed inside a function you need to pass them by reference. To do that you need to make some changes in your function definition:
void getdata(char* &name, int &born_year, int &married_year) {
//things you function does
}
Everything looks fine. Just you need to call 'function by reference' to directly change values of class variable.
https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm
void getdata(char* name, int born_year,int married_year)
you can remove variables declared in main function and use p. before every parameter.
getdata(p.name, p.born_year, p.married_year);
As others have mentioned your problem was that you were passing copies of the values in, not the variables themselves. Also you forgot to put the "p" on "married_year" in your main loop.
However, rather than passing in the separate values by reference, a much nicer idea is passing in a reference to the whole person:
int main(void) {
person p;
getdata(p);
print(p);
return 0;
}
Getdata and print would look like this:
void getdata(person &p) {
cout << "Enter Name!\n > ";
cin.getline(p.name, 19);
cout << "What's the Born Year?\n > ";
cin >> p.born_year;
cout << "What's the Married Year?\n > ";
cin >> p.married_year;
}
void print(const person &p) {
cout << "Your Name : " << *(p.name);
cout << "\n Your Born Year : " << p.born_year;
cout << "\n Your Married Year : " << p.married_year;
}
It's a cleaner way to do it, and since you're not creating or passing as many variables around, there are less ways to make a mistake here. If you made the fields private however, you'd need to make the two functions "friend" of the class to access its members.

Calling for function, only returning 0

Alrighty, the goal of what I am trying to do right now is call the function getSingleStudentInfo, which contains the student's number, last name, and age. In the end this program is designed to do two things, the first being the single student info, the second, printing out an array of 20 students. Disregard the second part, as I have not really gotten into that part yet, so ignore anything involving vectors.
The problem that I am having is that in main the first thing that the program will do is ask you to press 1 for the single info or 2 for the full 20 peoples info. The program compiles fine, but what happens is, no matter what number you enter, the program will say "process returned 0 (0x0)" and be done, I'm having a hard time figuring out why it is doing that instead of printing out the single students info, being "student's ID number is 400" "student's last name is: Simmons" "student's age is: 20"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
};
Student s;
int selection;
vector<int> studentNumber (20);
vector<string> lastName;
vector<int> age (20);
void getSingleStudentInfo (int studentNumber, string lastName, int age) {
cout << "Student's ID number is: ";
cout << s.studentNumber << endl;
cout << "Student's last name is: ";
cout << s.lastName << endl;
cout << "Student's age is: ";
cout << s.age << endl;
return;
};
int main()
{
cout << "Press '1' to see a single student data entry" << endl;
cout << "Press '2' to see all 20 student records" << endl;
cin >> selection;
if (selection == 1) {
getSingleStudentInfo;
};
/*for (vector<int>::size_type i = 0; i <= 20; i++)
{
cout << "Student's ID number is: " << 400 + i << endl;
}
return 0;*/
}
You need to call the function, e.g.
if (selection == 1)
{
getSingleStudentInfo(7, "Johnson", 20);
}
However, it seems like by the implementation, this should be a method off of the student itself
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
void getSingleStudentInfo() const;
};
Then you'd call it off a Student instance
Student s{400, "Simmons", 20};
s.getSingleStudentInfo();
Then if you had a vector of Student you could do
std::vector<Student> students; // assume this has been populated
std::for_each(begin(students),
end(students),
[](const Student& s){s.getSingleStudentInfo();});
To print in columns, you could change your function to something like
void Student::getSingleStudentInfo()
{
cout << s.studentNumber << '\t'
<< s.lastName << '\t'
<< s.age << endl;
};