C++ functions won't return values - c++

#include<iostream>
#include<cstdlib>
#include<string>
#include<time.h>
using namespace std;
//Functions
// player strategy
int strategy(int user1Strat, int user2Strat);
// player total score per round
int currentScore();
// Display game result
void printResults();
int main()
{
int total_player1 = 0; // player 1 current score
int total_player2 = 0; // player 2 current score
int player1_strat= 0; //player 1 strategy for each turn
int player2_strat = 0; // player 2 strategy for each turn
// seed the random number generator.
srand(static_cast<int> (time(NULL)));
// get strategy for each player using functions <strategy>
strategy(player1_strat, player2_strat);
cout << player1_strat << endl << player2_strat << endl;
system("pause");
return 0;
}
int strategy(int user1Strat, int user2Strat)
{
int x,
y;
cout << "Enter player1's roll until strategy: ";
cin >> user1Strat;
cout << "Enter player2's roll until strategy: ";
cin >> user2Strat;
x = user1Strat;
y = user2Strat;
return x, y;
}
While calling for function strategy in the function main it will execute how it should, but once I ask to return the value it will just return
Enter player1's roll until strategy: 10
Enter player2's roll until strategy: 5
0
0
press any key to contiue...
Does anyone know why this is happening or what is causing it, was my error in the strategy function? Or upon calling it?

strategy(player1_strat, player2_strat); in your main() do nothing after receiving inputs so you won't see any change on player1_strat and player2_strat.
If you want to modify player1_strat and player2_strat in strategy, you could do that by referencing:
void strategy(int& user1Strat, int& user2Strat)
{
cout << "Enter player1's roll until strategy: ";
cin >> user1Strat;
cout << "Enter player2's roll until strategy: ";
cin >> user2Strat;
}
or you could return "multiple value" by using std::pair:
//#include <utility>
std::pair<int, int> strategy(int user1Strat, int user2Strat)
{
int x, y;
cout << "Enter player1's roll until strategy: ";
cin >> user1Strat;
cout << "Enter player2's roll until strategy: ";
cin >> user2Strat;
x = user1Strat;
y = user2Strat;
return std::make_pair(x, y);
}
//main()
std::pair<int, int> result = strategy(player1_strat, player2_strat);
x = result.first;
y = result.second;

You can only return a single object from a function. return x, y; does not return x and y but only y. If you want to update multiple variables, give them to the function as references and change their value inside the function.
Edit:
As mentioned by #Keith Thompson in the comments, the comma actually is an operator in this statement. It evaluates x (not much to do there), discards the result and then evaluates and returns the second argument y.

Related

How can I save a string input with blank space in c++ (I am using if else statement)

So I am trying to make a text multiplier , here is the code
#include <iostream>
using namespace std;
int main()
{
bool m, n;
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin >> x;
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Everything was fine until I came to know that it was not saving the text input with a blank space
I searched how to store string input with blank space and then changed the code but it didn't work.
The changed code was
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Please help
List item
If I understand what you want to do, you need to read the integer value, clear the remaining '\n' that is left in stdin by operator>>, and then use getline() to read the text you want to multiply, e.g.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
if (!(cin >> y)) { /* validate stream-state after EVERY input */
std::cerr << "error: invalid integer input.\n";
return 1;
}
/* clear remaining '\n' from stdin (and any other characters) */
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "enter the text you want to multiply : ";
if (!getline (cin, x)) { /* validate stream state */
std::cout << "user canceled input.\n";
return 0;
}
for (int a = 1; a <= y; ++a)
cout << x << endl;
return 0;
}
Note: the use of isdigit(y) is superfluous. If you validate the input correctly, you determine whether a valid integer was entered at the time of the read simply by checking the stream-state after the read. If failbit is set, the user did not enter a valid integer.
While fine for test code, you will want to look at Why is “using namespace std;” considered bad practice?
Example Use/Output
$ ./bin/multiplytext
enter how many times you want to multiply the text : 3
enter the text you want to multiply : my dog has fleas
my dog has fleas
my dog has fleas
my dog has fleas
If I misinterpreted your goal, let me know and I'm happy to help further.
As seen from this answer, you are mixing the >> operator and getline() which causes syncing issues as getline is not waiting for the input to flush.
You can call either
cin.ignore();
or
cin.clear();
cin.sync();
just before getline().
Patched code:
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.ignore();
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}

always returning 466750944 in c++ calculations script

#include <iostream>
using namespace std;
multiplication() {
int x;
int y;
int sum;
sum = y * x;
cout << "multiplication" << endl;
cout << "enter first number for multiplication: ";
cin >> x;
cout << "enter second number for multiplication: ";
cin >> y;
cout << "your product is: " << sum <<endl;
return 0;
}
void division (){
cout << "division" << endl;
}
void addition (){
int y;
int x;
int sum = x * y;
cin >> x;
cin >> y;
cout << sum;
}
void subtraction (){
}
int main()
{cout << "enter 1 for multiplication, enter 2 for division, enter 3 for addition, and enter 4 for subtraction"<<endl;
int math;
cin >> math;
switch(math){
case 1:
multiplication();
break;
case 2:
division();
default:
cout << "it dont work ooga booga"<<endl;
break;
case 3:
addition ();
break;
case 4:
subtraction();}
return 0;
}
this is the script i am trying to run, im running in code::blocks if something is wrong that would cause it to always return 466750944 please tell me so i could work more on this, this may be my a problem with codeblocks if someone could also run this script in codeblocks or another ide and post their results it would be very much appreciated, thank you
When you say sum = x * y that is evaluated at the point of definition, it's not a formula as in math where later on it's evaluated when rendered.
When the sum = x * y statement is executed, x and y are not initialized so the value of sum is basically garbage.
To see this behaviour in action, step through your code in a debugger and look at the values of x, y and sum.
Either move that to after x and y are properly defined, or move it to a function, like:
int sum(int x, int y) {
return x * y;
}

How do I prevent this loop? C++

I'm new to C++ and stack overflow in general so please excuse me if a make a mistake somewhere.
I posted my code down below, but my issue is that when I type either yes or no at after the calculation is complete, no is supposed to end the program (which I was still working on) and yes is supposed to set it up for another calculation.
However I end up with a glitchy loop.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
bool b;
bool yes = b;
do {
float x;
float y;
float z;
float a;
cout << "Enter The amount you are investing:" << endl;
cin >> x;
cout << "Enter the rate:" << endl;
cin >> y;
cout << "Enter the investment period (years):" << endl;
cin >> z;
cout << "Enter the compounding period:" << endl;
cin >> a;
cout << pow((1 + y / a), (a*z))*x << endl << "Want to do another? (yes/no)";
cin >> b;
cin.ignore();
} while (yes = true); {
cin.clear();
if (b = yes) {
}
else {
}
}
return 0;
}
The behaviour of your code is probably due to:
unintentional reassignment of the termination condition bool value: yes to: true, instead of checking its value, which is done with ==, not with the assignment =.
no modification of the value yes within the while loop.
A possible update is:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// initialise the sentinel
bool yes = true;
do {
// define variables
float x, y, z, a;
// read input
cout << "Enter The amount you are investing:" << endl;
cin >> x;
cout << "Enter the rate:" << endl;
cin >> y;
cout << "Enter the investment period (years):" << endl;
cin >> z;
cout << "Enter the compounding period:" << endl;
cin >> a;
cout << pow((1 + y / a), a * z) * x << endl;
// redo calculation or exit
cout << "Want to do another? (yes/no)";
cin >> yes;
// check termination condition
} while (yes == true);
return 0;
}
Additionally, watch out for the uninitialised variables: x, y, z, a and think for a proper default value that will indicate possible wrong result.
Lastly, withing the calculation: 1 + y / a is ambiguous, it could mean both: (1 + y) / a and: 1 + (y / a), put parentheses to enforce precedence in the wanted order.
You are not modifying the value of variable yes. It is always set to true.

My program for calculating the final grade doesn't calculate it and I can't tell why

I've been trying to write a C++ program that calculates your end of year grade (an exercise given by the Google for Education C++ course). The program works, except for the fact that it doesn't calculate your final grade, instead, it just outputs "0". I have searched the code and can't seem to find the problem.
#include <iostream>
using namespace std;
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return 0;
}
}
int assignments() {
int assignment1 = 0;
int assignment2 = 0;
int assignment3 = 0;
int assignment4 = 0;
cout << "Enter the score for the first assignment. ";
check(assignment1);
cout << "Enter the score for the second assignment. ";
check(assignment2);
cout << "Enter the score for the third assignment. ";
check(assignment3);
cout << "Enter the score for the fourth assignment. ";
check(assignment4);
return ((assignment1 + assignment2 + assignment3 + assignment4) / 4 * 0.4);
}
int mid() {
int midterm = 0;
cout << "Enter the score for the midterm. ";
check(midterm);
return (midterm * 0.15);
}
int finalex() {
int finals = 0;
cout << "Enter the score for the final. ";
check(finals);
return (finals * 0.35);
}
int participation() {
int parti = 0;
cout << "Enter the class participation grade. ";
check(parti);
return (parti * 0.1);
}
int main() {
int assign = assignments();
int midt = mid();
int fingra = finalex();
int partigra = participation();
cout << "The final grade is: " << assign + midt + fingra + partigra << endl;
}
(The reason I have a different program for every grade type is because the course states that you should make as many functions as possible)
Either you should pass value to check() as reference or make check to return input value.
Change
int check(int a)
to
int check(int& a)
Second method
Modify check to
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return a;
}
}
And use return value to assign input to variables. Like
int midterm = 0;
cout << "Enter the score for the midterm. ";
midterm=check(midterm);
Your cin >> a statements updates value of a local variable which is gone as soon as check() returns. You want to update value of variables that are actually used for calculating grades. Just change the function check() to pass by reference check(int &a) or pass a pointer check(int *a)

Loop in function running more than it needs to

In a problem i am working on i have a function that checks if the number of spherical and cylindrical holes in rectangular block are greater than zero. In this problem i have to call the function twice. My problem is that the first time i call the function 'HoleCheck' is is running twice and assuming that zero is entered in for the cylindrical holes and makes me re-enter the value for spherical holes. How can i make it to only run once for the spherical hole check?
#include <iostream>
#include <string>
using namespace std;
void Check(double arr1[], string arr2[]);
void HoleCheck(int arr3[], string arr4[]);
int main()
{
double DimArray[3];
string MyArray[3] = { "Height", "Length", "Width"};
int totalholes[2];
string holes[2] = { "Spherical", "cylindrical"};
cout << "Enter the height, length and width of rectangle in centimeters: ";
cin >> DimArray[0] >> DimArray[1] >> DimArray[2];
Check(DimArray, MyArray);
cout << "How many spherical bubbles are present? ";
cin >> totalholes[0];
HoleCheck(totalholes, holes);
cout << "How many cylindrical holes are present? ";
cin >> totalholes[1];
HoleCheck(totalholes, holes);
return 0;
}
void Check(double arr1[], string arr2[])
{
int i;
for (i = 0; i < 3; i++)
{
while (arr1[i] <= 0)
{
cout << "Your entered " << arr2[i] << " is less than zero!\n";
cout << "Please re-enter a valid number --> ";
cin >> arr1[i];
}
}
}
void Check(double arr1[], string arr2[])
{
int z;
for (z = 0; z < 2; z++)
{
while (arr3[z] <= 0)
{
cout << "The number of " << arr4[z] << " holes must be greater than 0.\n";
cout << "Please re-enter a valid number --> ";
cin >> arr3[z];
}
}
}
Assuming that your second Check function is actually HoleCheck and that was a typo:
Your HoleCheck Function checks both elements of its arr3, but you are calling it before you enter any values into totalHoles[1].
Either just remove the first call to HoleCheck or change it so you can tell it which entry in the array to check.