I am slowly trying to learn c++ on my own and got stuck using functions. I did find a way to get past the initial problem but I have no idea why I couldn't do it the way I first intended to. Here's the working program.
// ex 6, ch 2
#include <iostream>
using namespace std;
void time(int, int);
int main()
{
int h, m;
cout << "Enter the number of hours: ";
cin >> h;
cout << endl;
cout << "Enter the number of minutes: ";
cin >> m;
cout << endl;
time(h, m);
cin.get();
cin.get();
return 0;
}
void time(int hr, int mn)
{
cout << "The time is " << hr << ":" << mn;
}
And here is how I would like to do it.
// ex 6, ch 2
#include <iostream>
using namespace std;
void time(int, int);
int main()
{
int h, m;
cout << "Enter the number of hours: ";
cin >> h;
cout << endl;
cout << "Enter the number of minutes: ";
cin >> m;
cout << endl;
cout << "The time is " << time(h, m);
cin.get();
cin.get();
return 0;
}
void time(int hr, int mn)
{
cout << hr << ":" << mn;
}
In my head both of them would return the same thing but my compiler thinks otherwise (and I would like to know why).
Edit: It seems to work like this for some odd reason.
cout << "The time is ";
time(h, m);
If nothing more, it just made me more confused.
cout << "The time is " << time(h, m);
time does not return anything, but to send something to cout in this case would require it to return a value (probably a string in this case) vs having the time function call cout directly.
You need to edit your time-function to return a string. I'm using stringstream to convert int to string.
#include <sstream>
...
string time(int, int);
...
string time(int hr, int mn)
{
stringstream sstm;
sstm << hr << ":" << mn;
string result = sstm.str();
return result;
}
Now you can use it directly, like:
cout << "The time is " << time(h, m);
Related
I am trying to create a program where you enter two values in individual functions and then print them out in the main function. But I am having an error stating that my function is not returning values.
#include <iostream>
#include <iomanip>
using namespace std;
void welcome();
double mass(double m);
double freqnat(double nf);
int main()
{
double attachedmass = 0;
double naturalfrequency = 0;
welcome();
mass(attachedmass);
freqnat(naturalfrequency);
cout << attachedmass << setw(20) << naturalfrequency << endl;
}
void welcome()
{
cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl;
system("pause");
cout << endl;
}
double mass(double m)
{
cout << "Please enter your desired mass." << endl << endl;
cin >> m;
}
double freqnat(double nf)
{
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> nf;
}
I tried using return m; and return nf; at the end of the functions, hoping this would tell the function to return the values inputted by the user. Instead, the program does run but the values print out as zeroes.
You need to return values AND store them somewhere:
// storing results in variables
attachedmass = mass(attachedmass);
naturalfrequency = freqnat(naturalfrequency);
Your functions should be:
double mass(double m)
{
cout << "Please enter your desired mass." << endl << endl;
cin >> m;
return m;
}
double freqnat(double nf)
{
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> nf;
return nf;
}
Having said this, you don't need to pass any parameters at all to the functions for this. They can be something like this:
#include <iostream>
#include <iomanip>
using namespace std;
void welcome()
{
cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl;
cout << endl;
}
double mass()
{
double user_in;
cout << "Please enter your desired mass." << endl << endl;
cin >> user_in;
return user_in;
}
double freqnat()
{
double user_in;
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> user_in;
return user_in;
}
int main()
{
double attachedmass = 0;
double naturalfrequency = 0;
welcome();
attachedmass = mass();
naturalfrequency = freqnat();
cout << attachedmass << setw(20) << naturalfrequency << endl;
}
So with youre program you are using the functions but you are not assigning the return value to anything so the two double values will not change, you will probably want to pass the doubles in by reference like this:
double mass(double& m);
and
double freqnat(double& nf);
Before you werent changing the two double values atall so they would not change but now you are passing them by reference which means you can change them.
Also you will not need to return anything so you can just make mass and freqnat's return type void as you just passed a reference to it. So the working program would be:
#include <iostream>
#include <iomanip>
using namespace std;
void welcome();
double mass(double m);
double freqnat(double nf);
int main()
{
double attachedmass = 0;
double naturalfrequency = 0;
welcome();
mass(attachedmass);
freqnat(naturalfrequency);
cout << attachedmass << setw(20) << naturalfrequency << endl;
}
void welcome()
{
cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl;
system("pause");
cout << endl;
}
void mass(double& m)
{
cout << "Please enter your desired mass." << endl << endl;
cin >> m;
}
void freqnat(double& nf)
{
cout << "Please enter your desired natural frequency." << endl << endl;
cin >> nf;
}
#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;
I'm working on a program in C++ to make schedules for me, since I have a hard time focusing on school work. The code will make priorities of assignments based on the due dates, duration to do the assignments, etc.
Anyway, I've run into a massive problem. I'm trying to assign a class variable's name to a variable! For example:
string a = "assignmentName" Class a(); //a is a variable and it's supposed to put the class's name as assignmentName
If you don't think this way will work, please tell me other solutions!
Also, I'm still a beginner, so please try to explain a little simple!
Here's the code:
#include <string>
#include <iostream>
using namespace std;
class Assignment
{
private:
int duration = 30; //Amount of time per assignment (in minutes)
int due = 1; //Amount of days till its due, if it's one then the assignment is due in 1 days
string name; //Name of assignment
public:
Assignment(int, int, string);
~Assignment();
void setDuration(int duration) {this -> duration = duration;}
void setDue(int due) {this -> due = due;}
void setDue(int name) {this -> name = name;}
int getDuration() { return duration; }
int getDue() { return due; }
string getName() { return name; }
};
Assignment::Assignment (int duration, int due, string name) //Constructor Method
{
this -> duration = duration;
this -> due = due;
this -> name = name;
}
Assignment::~Assignment() //Destructor Method
{
cout << "Assignment Object Destroyed" << endl;
}
int main()
{
int assignmentAmount;
int i;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
for (i = 0; i < assignmentAmount; i++){
cout << "Enter assignment" << i <<"'s " << "duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment" << i << "'s " << "due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment" << i <<"'s " << "name: ";
cin >> userInput3 >> endl;
Assignment i(userInput1, userInput2, userInput3); //I is the class's number and it's supposed to be a variable
}
return 0;
}
What you are looking for is an array of Assignment objects, eg:
int main()
{
Assignment *assignments;
int assignmentAmount;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
assignments = new Assignment[assignmentAmount];
for (int i = 0; i < assignmentAmount; i++){
cout << "Enter assignment " << i << "'s duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment " << i << "'s due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment " << i <<"'s name: ";
cin >> userInput3 >> endl;
// either:
assignments[i] = Assignment(userInput1, userInput2, userInput3);
// or:
assignments[i].setDuration(userInput1);
assignments[i].setDue(userInput2);
assignments[i].setName(userInput3);
}
// use assignments and assignmentAmount as needed...
delete[] assignments;
return 0;
}
Though, you should use std::vector instead of new[] directly:
#include <vector>
...
int main()
{
std::vector<Assignment> assignment;
int assignmentAmount;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
for (int i = 0; i < assignmentAmount; i++){
cout << "Enter assignment " << i << "'s duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment " << i << "'s due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment " << i << "'s name: ";
cin >> userInput3 >> endl;
// either:
assignments.push_back(Assignment(userInput1, userInput2, userInput3));
// or:
assignments.emplace_back(userInput1, userInput2, userInput3);
}
// use assignments as needed...
return 0;
}
Or:
#include <vector>
...
int main()
{
std::vector<Assignment> assignment;
int assignmentAmount;
int userInput1;
int userInput2;
string userInput3;
cout << "Enter assignment amount: ";
cin >> assignmentAmount << "\n" << endl;
assignments.resize(assignmentAmount);
for (int i = 0; i < assignmentAmount; i++){
cout << "Enter assignment " << i << "'s duration: ";
cin >> userInput1 << endl;
cout << "Enter assignment " << i << "'s due date in days from now: ";
cin >> userInput2 >> endl;
cout << "Enter assignment " << i << "'s name: ";
cin >> userInput3 >> endl;
// either:
assignments[i] = Assignment(userInput1, userInput2, userInput3);
// or:
assignments[i].setDuration(userInput1);
assignments[i].setDue(userInput2);
assignments[i].setName(userInput3);
}
// use assignments as needed...
return 0;
}
You can't get variable names as a variable, since a variable is basically like an alias to the data, when your program gets compiled all these names, don't exist anymore.
The compiler does not emit symbol names to the executable (the debug version may have symbol names).
If you want to associate or map symbol names to variables, you will need to declare the variable global and place the address into some kind of table.
Example:
int my_global_int_a;
std::map<std::string, int *> variable_dictionary;
variable_dictionary["my_global_int_a"] = &my_global_int_a;
// Here's how to get the variable
const std::string variable_name = "my_global_int_a";
int * p_variable = nullptr;
p_variable = variable_dictionary[variable_name];
std::cout << *p_variable << std::endl;
You may want to give deep thought to the need of retaining variable names.
I'm new to programming (in general) and C++ (in particular) and currently learning classes and objects.
I've defined the following as an exercise:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
class X
{
public:
void setNum_1(int);
void setNum_2(int);
void setNum_3(int);
void setNum_4(int);
double getNum_1();
double getNum_2(int num_1);
double getNum_3(int num_1, int num_2);
double getNum_4(int num_1, int num_2, int num_3);
private:
int num_1;
int num_2;
int num_3;
int num_4;
};
int main()
{
X testObject;
int lNum_1 = 0;
int lNum_2 = 0;
int lNum_3 = 0;
int lNum_4 = 0;
cout << endl;
cout << "Please enter an integer: ";
cin >> lNum_1;
cout << "Please enter an integer: ";
cin >> lNum_2;
cout << "Please enter an integer: ";
cin >> lNum_3;
cout << "Please enter an integer: ";
cin >> lNum_4;
testObject.setNum_1(lNum_1);
testObject.setNum_2(lNum_2);
testObject.setNum_3(lNum_3);
testObject.setNum_4(lNum_4);
cout << endl;
cout << "The 1st number returned is: " << testObject.getNum_1() << endl;
cout << "The 2nd number returned is: " << testObject.getNum_2(lNum_1) << endl;
cout << "The 3rd number returned is: " << testObject.getNum_3(lNum_1, lNum_2) << endl;
cout << "The 4th number returned is: " << testObject.getNum_4(lNum_1, lNum_2, lNum_3) << endl;
cout << endl;
return 0;
}
void X::setNum_1(int n_1)
{
num_1 = n_1;
}
void X::setNum_2(int n_2)
{
num_2 = n_2;
}
void X::setNum_3(int n_3)
{
num_3 = n_3;
}
void X::setNum_4(int n_4)
{
num_4 = n_4;
}
double X::getNum_1()
{
return sqrt(num_1);
}
double X::getNum_2(int num_1)
{
return pow(num_2,3);
}
double X::getNum_3(int num_1, int num_2)
{
return num_1 * num_2;
}
double X::getNum_4(int num_1, int num_2, int num_3)
{
return (num_1 + num_2) / num_3;
}
Can anyone offer some guidance on how to modify this class so that it has only one member function with all of the arguments defaulted?
Thanks in advance,
Ryan
Ofcourse there are MANY ways to do this and most of them will be more elegant than what I have done here. But this should give you some ideas.
a. You should use the variables defined in the class
b. If you need to perform certain conditional operations in a function, use a switch case or an if statement. And decide the operation based on a parameter passed.
Again, many ways to make this more elegant, but this should get you started and thinking.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
class X
{
public:
void setNums(int, int, int, int);
double performOp(int);
private:
int num_1;
int num_2;
int num_3;
int num_4;
};
int main()
{
X testObject;
int lNum_1 = 0;
int lNum_2 = 0;
int lNum_3 = 0;
int lNum_4 = 0;
cout << endl;
cout << "Please enter an integer: ";
cin >> lNum_1;
cout << "Please enter an integer: ";
cin >> lNum_2;
cout << "Please enter an integer: ";
cin >> lNum_3;
cout << "Please enter an integer: ";
cin >> lNum_4;
testObject.setNums(lNum_1,lNum_2,lNum_3,lNum_4);
cout << endl;
cout << "The 1st number returned is: " << testObject.performOp(1) << endl;
cout << "The 2nd number returned is: " << testObject.performOp(2) << endl;
cout << "The 3rd number returned is: " << testObject.performOp(3) << endl;
cout << "The 4th number returned is: " << testObject.performOp(4) << endl;
cout << endl;
return 0;
}
void X::setNums(int n_1, int n_2, int n_3, int n_4)
{
num_1 = n_1;
num_2 = n_2;
num_3 = n_3;
num_4 = n_4;
}
double X::performOp(int n)
{
if(n == 1) return sqrt(num_1);
if(n == 2) return pow(num_2,3);
if(n == 3) return num_1 * num_2;
if(n == 4) return (num_1 + num_2) / num_3;
}
Any help would be greatly appreciated, my program quits as soon as i come out of the menu and try to enter something, been racking my brains trying to figure this out and is very annoying as i cant get anything else done until i fix this problem. i am a bit of a begginer at c++ so dont slate me if its a rookie mistake please haha!
This is the source code, its not yet a completed program just cant figure out whats wrong just now.
Thanks for any help!
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
struct cust
{
int employeeno, deptno;
char fname[10], sname[10], weekend[10];
float hours, othours, rate, otrate, normalpay, otpay, grosspay, netpay, totalni, totaltax, ni, tax;
};
int Menu(int& menuchoice);
void InputRecords(cust c[], int row, int menuchoice);
int Calculations(cust c[]);
int SearchNumber(cust c[], int &row);
int DeleteRecords();
int TotalPay();
int main()
{
struct cust c[100];
int menuchoice, row;
Menu(menuchoice);
if (menuchoice == 1){
system("CLS");
InputRecords(c, row, menuchoice);
}
if (menuchoice == 2){
system("CLS");
SearchNumber(c, row);
}
if (menuchoice == 3){
system("CLS");
DeleteRecords();
}
if (menuchoice == 4){
system("CLS");
}
if (menuchoice == 5){
system("CLS");
exit(5);
}
//Calculations(cust c[]);
}
int Menu(int& menuchoice){
cout << " \n\n\n\n\n 1. Input a Payslip" << endl << endl;;
cout << " 2. Read a Payslip " << endl << endl;
cout << " 3. " << endl << endl;
cout << " 4. " << endl << endl;
cout << " 5. Quit the Program" << endl << endl;
cin >> menuchoice;
}
void InputRecords(cust c[], int row, int menuchoice){
char another;
do{
cout << "Please Enter Their Employee Number: " << endl;
cin >> c[row].employeeno;
cout << "Please Enter Their First Name: " << endl;
cin >> c[row].fname,9;
cout << "Please Enter Their Second Name: " << endl;
cin >> c[row].sname,9;
cout << "Please Enter Their Department Number 1 - 9: " << endl;
cin >> c[row].deptno;
cout << "Please Enter The Hours They Have Worked: " << endl;
cin >> c[row].hours;
if (c[row].hours >= 37.5){
cout << "Please Enter Any Overtime They Have Worked: " << endl;
cin >> c[row].othours;
}
cout << "Please Enter Their Rate of Pay: " << endl;
cin >> c[row].rate;
cout << "Please Enter The Date of the Week End (DD/MM/YYYY): " << endl;
cin >> c[row].weekend, 9;
row++;
cout << endl;
//Putting it in the file.
ofstream timesheetFile("Timesheet.txt", ios::app);
if(timesheetFile.is_open()){
cout << "File has been opened." << endl;
timesheetFile << c[row].employeeno << " " << c[row].fname << " " << c[row].sname << " " << c[row].deptno << " " << c[row].hours << " " << c[row].othours << " " << c[row].rate << " " << c[row].weekend << "\n" << endl;
timesheetFile.close();
}else{
cout << "Error! File is not open." << endl;
}
cout << "Would you like to enter another record? Y/N : ";
cin >> another;
cout << endl << endl;
}while(row<100 && another == 'y');
system("CLS");
main();
}
//read records
int SearchNumber(cust c[], int &row){
//system("CLS");
int empno;
cout << "Enter Employee Number : ";
cin >> empno;
for (int i=0; i < row; i++)
{
if (empno == c[i].employeeno){
system("CLS");
cout << c[i].employeeno << endl << c[i].fname << c[i].sname << endl;
}
}
}
//deleterecords
int DeleteRecords(){
}
//calculations
int Calculations(float normalpay, float& hours, float& rate, float otpay, float otrate, float& othours, float grosspay, float tax, float ni, float netpay, float totalni, float totaltax){
ni = 6.8 / 100;
tax = 12.75 / 100;
otrate = 1.5 * rate;
normalpay = hours * rate ;
otpay = otrate * othours;
grosspay = normalpay + otpay;
totalni = grosspay * ni;
totaltax = tax * grosspay;
netpay = normalpay + otpay - totaltax - totalni;
// cout << totaltax << endl;
//
// cout << totalni << endl;
//
// cout << netpay << endl;
}
int TotalPay(){
}
The problem is here
int main()
{
struct cust c[100];
int menuchoice, row;
Menu(menuchoice);
if (menuchoice == 1){
system("CLS");
InputRecords(c, row, menuchoice);
}
You have not given the variable row a value but you use row when you call InputRecords.
From a look at your code it seems to me that the row variable should be moved to the InputRecords function and initalised to zero there. I can't see why you have the row variable in the main function.
Also I can't see why you pass menuchoice to InputRecords, it doesn't get used there. It all seems a bit random, maybe you should review functions and parameter passing.
Looks like your row variable is never being initialized. Why is this?
It's also good practice to initialize your variables like menuchoice
int Menu(int& menuchoice);
void InputRecords(cust c[], int row, int menuchoice);// declared
int Calculations(cust c[]);
int SearchNumber(cust c[], int &row);
int DeleteRecords();
int TotalPay();
int main()
{
struct cust c[100];
int menuchoice, row; // declared again but never initialized
Menu(menuchoice);
if (menuchoice == 1){
system("CLS");
InputRecords(c, row, menuchoice); // used