Using Pointers in functions - c++

I am trying to use a pointer in my function and then call the function from my main body. When I try to call it I get these 2 errors'; "undefined reference to string output which is caused by the line where I call my stringOutput(); function and the other error is "Id returned 1 exit status." I'm not sure why these errors are occurring.
void stringOutput(int dayNumber, double *ptrTemperatures);
int main()
{
int dayNumber;
double fahrenheit = 0;
double cTemperature = 0;
const double MAXIMUM_TEMPERATURE = 60;// constants for mix/max
const double MINIMUM_TEMPERATURE = -90 ;
const int MAXIMUM_DAYS = 365;
const int MINIMUM_DAYS = 1;
double *ptrTemperatures = NULL;
cout << "How many days would you like to enter? ";
dayNumber = myValidation::GetValidInteger(MINIMUM_DAYS, MAXIMUM_DAYS);
try
{
ptrTemperatures = new double[dayNumber];
}
catch(exception e)
{
cout << "Failed to allocate memory: " << e.what() << endl;
}
cout << "\n\nTEMPERATURE REPORTER\n____________________________\n Please Enter the temperature for each day.";
for(int dayCount = 0; dayCount < dayNumber; dayCount++){
cout << "Celsius Temperature for Day " << (dayCount + 1) << ": ";
ptrTemperatures[dayCount] = myValidation::GetValidDouble(MINIMUM_TEMPERATURE, MAXIMUM_TEMPERATURE);
}
stringOutput();
delete[] ptrTemperatures;
return 0;
}//end main
void stringOutput(int dayNumber, double *ptrTemperatures)
{
cout << "DAILY TEMPERATURE REPORT\n__________________________________-\n\n";
for(int dayCounter = 0; dayCounter < dayNumber; dayCounter++)
{
cout << "Day " << dayCounter << (dayCounter+1) << setw(10) << celsiusToFahrenheit(ptrTemperatures[dayCounter]) << (char(248)) << "F"
<< setw(10) << ptrTemperatures[dayCounter] << (char(248)) << "C" << endl;
}
}

At a guess, your code looks roughly like this:
void stringOutput();
int main()
{
…
stringOutput();
}
void stringOutput(int dayNumber, double *ptrTemperatures)
{
…
}
Your main function uses the stringOutput function you declared above, but that function is never defined anywhere, hence the error.
Below main, you declare and define a separate overload of stringOutput, which has two parameters instead of none.
If you want to use the function you have below main, you need to declare it before main:
void stringOutput(int dayNumber, double *ptrTemperatures);
int main()
…
You also need to give it the arguments it needs, instead of giving it nothing:
int main()
{
…
stringOutput(dayNumber, ptrTemperatures);
}

Related

warning C4018: '<': signed/unsigned mismatch ONLY when I include Identical Functions

I am lost, when I ran my program last night it ran fine. When I added the power() function, suddenly lines which ran fine without adding the new code now trigger an error message:
warning C4018: '<': signed/unsigned mismatch
Why?
I feel I don't have the chops to explain this, so please follow the code below.
PLEASE RUN THE CODE WITH AND WITHOUT THIS power() FUNCTION. When run with the power() function, it makes error C4018 on the for loops in the exam() function! When run without the power() function, it runs FINE!!
#include <string>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
///the offending function///
double power(double base, int exponent)
{
double product;
//double base; int exponent;
std::cout << "enter a value for base: " << endl;
std::cin >> base;
std::cout << "enter exponenent: " << endl;
std::cin >> exponent;
double result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * base;
//product = base exponent;
}
std::cout << product;
return product;
}
///after here, things run fine if you X out the aforementioned function! Wow!
void exam()
{
std::vector<int> scores;
int F;
F = 0; //string names;
std::cout << "enter exam scores int:" << endl;
//std::vector <string> names;
while (F != -1)
{
std::cout << "Enter a new exame score:" << endl;
std::cin >> F;
scores.push_back(F);
}
if (F == -1)
{
std::cout << "end of score entering" << endl;
}
for (int i = 0; i < scores.size(); i++)
{
std::cout << scores[i];
}
/*
while (i < scores.size())
{
std::cout << scores[i];
i++;
}
*/
std::cout << "yay you made this work!!!!!!!!!!!!!" << endl;
}
int multiply()
{
int a;
int b;
a = 8;
b = 4;
std::cout << a * b << endl;
std::cout << "f*** yeah" << endl << endl;
return 0;
}
void test()
{
std::vector<int> newvector;
int T;
std::cout << "enter vector variables: " << endl;
std::cin >> T;
newvector.push_back(T);
while (T != -1)
{
std::cout << "enter new vector variables T " << endl;
std::cin >> T;
newvector.push_back(T);
if (T == -1)
{
newvector.pop_back();
}
}
std::cout << "end of NewVector data inputs:" << endl;
for (int W = 0; W < newvector.size(); W++)
{
std::cout << newvector[W] << endl;
}
}
int main()
{
power(2, 3);
exam();
/*int result = multiply();
std::cout << "endl ;" << endl;
test();
system("pause"); */
multiply();
string name;
int a;
std::cout << "enter a variable for your name: " << endl;
std::getline(cin, name);
if (name == "aaron")
{
std::cout << " what a dumb name, aAron?" << endl;
}
else if (name == "todd")
{
std::cout << "what a dottly name, Todd" << endl;
}
else
{
std::cout << "your name = " << name << endl;
}
//std::vector <string>
std::vector<int> asdf;
std::cout << "enter an int for a" << endl;
std::cin >> a;
asdf.push_back(a);
while (a != -1)
{
std::cout << "enter another A: " << endl;
std::cin >> a;
asdf.push_back(a);
if (a == -1)
{
asdf.pop_back();
}
} //set var; checks if d<size(); if so, JUMP to std::cout<<; when finished with body, find after size(); == "d++", then refer back to declaration)
/*/ for(int G = 0; G<asdf.size(); G++)
{
std::cout << asdf[G] << endl;
} */
for (int i = 0; i < asdf.size(); i++)
{
std::cout << asdf[i] << "f*** it works!!!!!! " << endl;
}
for (int d = 0; d < asdf.size(); d++)
{ //htt ps://youtu.be/_1AwR-un4Hk?t=155
std::cout << asdf[d] << ", ";
}
std::cout << endl;
std::cout << std::accumulate(asdf.begin(), asdf.end(), 0);
//std::cout<<
system("pause");
return 0;
}
The presence of the power function should have no effect on this problem. Possibly you aren't seeing the warnings because without the power function the program does not compile.
In
for (int W = 0; W < newvector.size(); W++)
newvector.size() returns an unsigned integer. int W is a signed integer. You're getting exactly what you asked for.
You can change int W to vector<int>::size_type W (but the less verbose size_t W should also work) to make the error message go away, but this is an error where you would likely have to add more than 2 billion items to the vector to see manifest.
Solution:
for (vector<int>::size_type W = 0; W < newvector.size(); W++)
However this is a good place for a range-based for loop
for (const auto &val: newvector)
{
std::cout << val << endl;
}
By letting the compiler figure out all the sizes and types your life is much easier.
This is repeated several times throughout the code.
Re: WHEN RUN, It makes error C4018 -
YOU made that error (warning, actually), not "it".
That warning is reported by compiler, so you haven't run anything yet...
Your newly added function uses uninitialized variable product; in my version of Visual Studio it is an error.

simplify my code in C++ below

I want to create a program which is able to calculate the surface area, volume, and circumference. for your additional info, I am studying about function, I has just learned about C++ about a week.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int getPostP(string msgP)
{
int Ppost= 0.000;
do
{
cout << msgP << endl;
cin >> Ppost;
return Ppost;
} while(Ppost<= 0);
}
int getPostL(string msgL)
{
int Lpost= 0.000;
do
{
cout << msgL << endl;
cin >> Lpost;
return Lpost;
} while(Lpost<= 0);
}
int getPostT(string msgT)
{
int Tpost = 0.000;
do
{
cout << msgT << endl;
cin >> Tpost;
return Tpost;
} while(Tpost <= 0);
}
int surfaceArea(int Psur, int Lsur, int Tsur)
{
return (2*Psur*Lsur)+(2*Psur*Tsur)+(2*Lsur*Tsur);
}
int volume(int Pvol, int Lvol, int Tvol)
{
return (Pvol*Lvol*Tvol);
}
float circumference(int Pcir, int Lcir, int Tcir)
{
return 4*(Pcir+Lcir+Tcir);
}
int main()
{
int P = getPostP("enter the P of your block");
int L = getPostL("enter the L of your block");
int T = getPostT("enter the T of your block");
float surfAreaBlock = surfaceArea(P, L, T);
float volBlock = volume(P, L, T);
float cirBlock = circumference(P, L, T);
cout << "block which have P = " << P << " and L = " << L << " and T = "<< T << " have surface area = " <<
surfAreaBlock << " and volume = " << volBlock << " and cirBlock = " << cirBlock;
return 0;
}
Maybe one of you want to rewrite and add some comment, which parts are able to simplify, so I can understand easier.
First of all, it looks like you should make all of your integer inputs into double instead of int, since it's expected that your inputs won't necessarily be an exact integer amount (probably). Also you can get rid of all of your duplicate functions for entering the parameters. Change it to a single function and call that one for each variable.
double getInput(const std::string& prompt)
{
double input(0.0);
do
{
std::cout << prompt << "\n-> " << std::flush;
// forces input to be a double type
while (!(std::cin >> input))
{
std::cout << "\n-> " << std::flush;
std::cin.clear();
std::cin.ignore(256, '\n'); ///< could use streamsize::max here
}
} while (input <= 0.0); ///< make sure it's positive
return input;
}

Error Variable is Protected

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void armySkirmish();
void battleOutcome();
string commander = "";
int numberOfHumans = 0;
int numberOfZombies = 0;
class ArmyValues
{
protected:
double attackPower;
double defensePower;
double healthPoints;
public:
void setAttackPower(double a)
{
attackPower = a;
}
void setDefensePower(double d)
{
defensePower = d;
}
void setHealthPoints(double h)
{
healthPoints = h * (defensePower * .1);
}
};
class Zombies: public ArmyValues
{
};
class Humans: public ArmyValues
{
};
int main(int argc, char ** argv)
{
cout << "Input Commander's Name: " << endl;
cin >> commander;
cout << "Enter Number of Human Warriors: " << endl;
cin >> numberOfHumans;
cout << "Enter Number of Zombie Warriors: " << endl;
cin >> numberOfZombies;
armySkirmish();
battleOutcome();
return 0;
}
void armySkirmish()
{
cout << "\nThe Humans tense as the sound of the undead shuffle towards them." << endl;
cout << commander << " shuffles forward with a determined look." << endl;
cout << "The undead form up into ranks and growl a war chant!" << endl;
cout << commander <<" shouts, CHARGE!!!" << endl;
cout << endl;
cout << "Warriors from both sides blitz across the field!" << endl;
cout << endl;
cout << "*The Carnage has begun!*" << endl;
cout << "*Steal, Sparks, and Flesh flies" << endl;
}
void battleOutcome()
{
int zombieLives = numberOfZombies;
int humanLives = numberOfHumans;
int randomNumber = 0;
int humanDeath = 0;
int zombieDeath = 0;
double newHumanLife = 0;
double newZombieLife = 0;
Zombies zombieBattleData;
Humans humanBattleData;
srand(time(NULL));
zombieBattleData.setAttackPower(20.0);
humanBattleData.setAttackPower(35.0);
zombieBattleData.setDefensePower(15.0);
humanBattleData.setDefensePower(20.0);
zombieBattleData.setHealthPoints(150.0);
humanBattleData.setHealthPoints(300.0);
while(zombieLives && humanLives > 0)
{
randomNumber = 1+(rand()%10);
if(randomNumber < 6)
{
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
if(newHumanLife <= 0)
{
humanLives--;
humanDeath++;
}
}else
{
newZombieLife = zombieBattleData.healthPoints - humanBattleData.attackPower;
if(newZombieLife <= 0)
{
zombieLives--;
zombieDeath++;
}
}
}
if(zombieLives <= 0)
{
cout << "Humans have emerged victorious!" << endl;
cout << "Human Deaths: " << humanDeath << "Zombie Deaths: " << zombieDeath << endl;
}else if(humanLives <= 0)
{
cout << "Zombies have emerges victorious!" << endl;
cout << "Human Deaths: " << humanDeath << "Zombie Deaths: " << zombieDeath << endl;
}
I know the code wont run properly as of now. What I was doing was a test run to make sure I was receiving no errors. The two errors I'm getting are:
armySimulatorMain.cpp:25:10: error: 'double ArmyValues::healthPoints' is protected
armySimulatorMain.cpp:115:67: error: within this context.
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
This is the case for Attack Power and Health Power however, Defense power is clearing the errors. i don't understand why they are getting flagged. I'm changing the variable through the public function so shouldn't this be allowed?
Also, I'm calling three variables outside of all functions because they are being used by multiple functions. How can I plug those variables somewhere I don't like that they are floating freely above everything?
Thanks guys I can't believe I forgot about getters... Anyway the code runs now much appreciated I'll make sure to remember this time xD
It's not complaining about the line where you set the values; as you say, that uses a public function. But here, you try to read the protected member variables:
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
You only try to read two variables, and those are the ones it complains about.
You'll need a public getter function to read the values.
You need to do something like:
public:
double gethealthPoints()
{
return healthPoints;
}
because attackPower, defensePower, healthPoints are all protected, so if you want to access to any of them you need a getter, otherwise you will always receive an protect error

Unresolved External Symbol with a particular function in c++

I got the error message like the following:
Unresolved External Symbol error with calculatewinner Candidate
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
void headerforelection();
void getNamecalculatetotal(ifstream& in, string candidates[], double Votes[], double percentvotes[]);
void getNamecalculatetotal2(ifstream& in, string fname[], double Votes[], double percentvotes[]);
void allvotes(double []);
void Votesrecievedpercentage(ifstream& in, char Candidate[], double Votes[], string fname[], double percentvotes[]);
void Votesrecievedpercentage2(double Votes[], string fname[], double percentvotes[]);
void calculatewinner(string fname[], double Votes[]);
void headerforelection();
int main()
{
ifstream in = ifstream();
in.open("Votes.txt");
ofstream out = ofstream();
out.open("outputs.txt");
char winner();
char Candidate();
string fname[5];
double Votes[5];
double percentvotes[5];
double total = double();
headerforelection();
while (!in.eof())
{
getNamecalculatetotal(in, fname, Votes, percentvotes);
Votesrecievedpercentage2(Votes, fname, percentvotes);
}
allvotes(Votes);
calculatewinner(fname, Votes);
}
void getNamecalculatetotal(ifstream& in, string fname[], double Votes[], double percent[])
{
double total = double();
for (int i = 0; i < 5; i++)
{
in >> fname[i] >> Votes[i];
total = total + Votes[i];
}
for (int j = 0; j < 5; j++)
{
percent[j] = (Votes[j] / total) * 100;
}
}
void headerforelection()
{
std::cout << fixed << setfill(' ') << left << setw(10) << "Candidate"
<< right << setw(20) << setprecision(0) << "votes Recieved"
<< right << setw(20) << setprecision(2) << "% of Total Votes" << std::endl;
std::cout << endl;
}
void Votesrecievedpercentage2( double Votes[], string fname[], double percentvotes[])
{
for (int b = 0; b < 5; b++)
{
std::cout << fixed << setfill(' ') << left << setw(10) << fname[b]
<< right << setw(16) << setprecision(0) << Votes[b]
<< right << setw(16) << setprecision(2) << percentvotes << std::endl;
}
}
void allvotes(double Votes[])
{
double total = double();
for (int i = 0; i < 5; i++)
{
total = total + Votes[i];
}
std::cout << setfill(' ') << left << setw(22) << "Total" << setprecision(0) << total << std::endl;
}
void calculatewinner(string fname[], double Votes[])
{
{
int winner = 0;
for (int l = 0; l, 5; l++)
{
if (Votes[l] > Votes[winner])
{
winner = l;//3
}
}
}
char winner();
char Candidate();
std::cout << std::endl;
std::cout << Candidate << "Is The Winner" << fname << "." << std::endl;
}
First to answer your question, change these lines
char winner();
char Candidate();
everywhere in your code (in main as well as in calculatewinner) to the following:
char winner;
char Candidate;
By adding the paranthesis you are actually declaring a prototype to a function. Since you never define a function Candidate(void) the linker complains about the missing implementation. This would apply to char winner() also, but since you never use this "variable", the linker isn't concerned about this one.
Otherwise, your code is very broken. I am sure you are just learning C++, but your code is quite inconsistent in naming conventions as well as some other errors that should be addressed before doing something else.

Classes(Odometer)- Error Message

I was wondering if anyone could give me a clue as to what these error messages mean when I try to compile my code.
Here is the error I get:
in function 'int main()':
not match for 'operator<<'in 'std::operator<<[with_Traits = std::char_traits(((std::basic_ostr...
and it repeats for a while.
I want to post my full code just so you have a idea of what my assignment is, it not that long! =)
#include <iostream>
#include <cstdlib>
using namespace std;
class Odometer
{
public:
Odometer();
void reset();
void totalfuel();
void input_miles(int getmiles);
void Odometer::set_fuel_efficiency(double fuel_efficiency);
int gallonsUsed;
private:
int milesDriven;
double fuel_efficiency;
int getmiles;
};
Odometer::Odometer()
{
milesDriven = 0;
fuel_efficiency = 0;
}
void Odometer::reset()
{
milesDriven = 0;
}
void Odometer::totalfuel()
{
fuel_efficiency = (milesDriven/gallonsUsed);
}
void Odometer::input_miles(int miles_driven)
{
milesDriven = milesDriven + miles_driven;
}
void Odometer::set_fuel_efficiency(double Fuel_efficiency)
{
fuel_efficiency = Fuel_efficiency;
}
double Odometer::getgallons()
{
return milesDriven/fuel_efficiency;
}
// ======================
// main function
// ======================
int main()
{
// Two test trips
Odometer trip1, trip2;
trip1.reset();
trip1.set_fuel_efficiency(45);
trip1.input_miles(100);
cout << "For your fuel-efficient small car:" << endl;
cout << "After 100 miles, " << trip1.totalfuel() << " gallons used." << endl;
trip1.input_miles(50);
cout << "After another 50 miles, " << trip1.totalfuel() << " gallons used." << endl;
trip2.reset();
trip2.set_fuel_efficiency(13);
trip2.input_miles(100);
cout << "For your gas guzzler:" << endl;
cout << "After 100 miles, " << trip2.totalfuel() << " gallons used." << endl;
trip2.input_miles(50);
cout << "After another 50 miles, " << trip2.totalfuel() << " gallons used." << endl;
system("PAUSE");
return 0;
}
What would you expect cout << void to print?
totalfuel() returns void, and you're passing it as a parameter to cout::operator <<. Did you mean to return something from the method?
Perhaps:
double Odometer::totalfuel()
{
fuel_efficiency = (milesDriven/gallonsUsed);
return fuel_efficiency;
}
totalFuel() returns void. I think you meant to invoke the getgallons() method instead.