I'm starting learning c++ and stepped on this problem, trying to make the following calculation: place + (place / 10)² which if place = 90 it should be 171.
#include <iostream>
#include <iomanip>
#include <cmath>
#include "TestFunction.h"
using namespace std;
int main() {
TestFunction test1 ("John", 90);
test1.getInfo();
}
here is the TestFunction header
#include <iostream>
#include <string>
#include <iomanip>
class TestFunction {
public:
TestFunction(std::string userName, int userPlace) {
name = userName;
place = userPlace;
}
int getPlace() {
return place;
}
int getResult() {
return num1;
}
void getInfo() {
std::cout << "Using getPlace():" << getPlace() << std::endl;
std::cout << "Using getResult(): " << getResult() << std::endl;
std::cout << "Using num1: " << num1 << std::endl;
std::cout << "calculate here: " << getPlace() + pow(getPlace() / 10, 2) << std::endl;
}
private:
std::string name;
int place;
int num1 = place + pow(place / 10, 2);
};
and get this result:
Using getPlace():90
Using getResult(): -2147483648
Using num1: -2147483648
calculate here: 171
I really don't know what I am missing when trying to use getResult() or num1, any advice or simple explanation will be welcome, thanks.
You need to keep track of when your calculations are done.
The init of num1 is done earlier than the initialisation of place, which is something to avoid at all cost.
You could move that calculation into the constructor:
TestFunction(std::string userName, int userPlace) {
name = userName;
place = userPlace;
num1 = place + pow(place / 10, 2);
}
There are other ways, but this is probably most accessable to you.
Related
So I'm unable to create a substring cut using ranges. I am making an airport program where you feed the program a txt.file and it has to divide the lines I get from it into different strings. For instance, I have the following text data:
CL903 LONDON 41000 14.35 08906 //number of flight, destination, price, etc.
UQ5723 SYDNEY 53090 23.20 12986
IC5984 TORONTO 18030 04.45 03260
AM608 TOKYO 41070 18.45 11315
so the first string will be on the lines of this (variables are in Spanish):
numVuelo[n] = M[n].substr(0,5)
this line will work perfectly, but when I move to the next one (from 7 to 14), it tells me that it's out of range, even though It's between the 0 and 31st values of the length of the string.
M[n] gets all of the strings on the text, I'm using Codeblocks and a class style with header and all. I'll copy the code below...
This is my header Vuelo.h:
#ifndef VUELO_H
#define VUELO_H
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
class Vuelo
{
public:
Vuelo(int N);
virtual ~Vuelo();
void setM();
void setNumVuelo(string _numVuelo, int n);
void setDestino(string _destino, int n);
void setPrecio(string _precio, int n);
private:
string M[NUM_FLIGHTS];
string numVuelo[NUM_FLIGHTS];
string destino[NUM_FLIGHTS+1]; //somehow "destino" doesn't work without the +1 but everything else does
float precio[NUM_FLIGHTS];
Then, on another code called Vuelo.cpp I have the following
#include "Vuelo.h"
Vuelo::Vuelo(int N)
{
M[N] = { };
numVuelo[N] = { };
destino[N] = { };
precio[N] = { };
}
Vuelo::~Vuelo()
{
//nope
}
void Vuelo::setM()
{
int c = 1;
string s;
ifstream F ("flights.txt");
if(F.is_open())
{
while (!F.eof())
{
getline(F,s);
M[c] = s;
cout << M[c] << endl;
c++;
}
//sets all values
for(c = 0; c < NUM_FLIGHTS; c++)
{
setNumVuelo(M[c],c);
setDestino(M[c],c);
setPrecio(M[c],c);
}
F.close();
}
else
{
cout << "ERROR document wasn't found" << endl;
}
}
void Vuelo::setNumVuelo(string _numVuelo, int n)
{
numVuelo[n]= _numVuelo.substr(0,5); //this works
cout << numVuelo[n] <<endl;
}
void Vuelo::setDestino(string _destino, int n)
{
destino[n] = _destino.substr(7, 13); //PROBLEM HERE
cout << destino[n] << " " << destino[n].length() << endl;
}
void Vuelo::setPrecio(string _precio, int n)
{
string p = _precio.substr(15,19); //PROBLEM HERE
precio[n] = atof(p.c_str());
cout << precio[n] <<endl;
}
And finally my main looks like this:
#include "Vuelo.h"
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
int main()
{
cout << "Bienvenido, reserva tu vuelo!" << endl;
cout << "-----------------------------------" << endl;
Vuelo* flight = new Vuelo(NUM_FLIGHTS);
flight->setM();
return 0;
}
Thanks :)
Im trying to make a number that is positive (already converted into a string) look like "+number" instead of "number" but i can't define it in an if
#include <iostream>
#include <string>
int main()
{
std::string x3s;
int number = 145;
if (number >= 0)
{
x3s = "+" + number;
}
std::cout << x3s << std::endl;
}
Firstly, there is an I/O manipulator std::showpos.
#include <iostream>
int main()
{
int number = 145;
std::cout << std::showpos << number << std::endl;
}
Secondly, you are using the verb "define" incorrectly.
You can use x3s = std::string("+") + std::to_string(number);
I have 2 .cpp files called "FactoringProgram.cpp" and "FactoringProgram2nd.cpp", also 1 header file called "FactoringProgram.h". I've already tried searching for this problem on StackOverflow and a couple other sites and haven't found a solution that worked for me. When I try to run this command: "g++ FactoringProgram.cpp FactoringProgram2nd.cpp" I get this error:
FactoringProgram.cpp: In function ‘int main()’: FactoringProgram.cpp:8:11: error: request for member ‘InitialMessage’
in ‘Problem1’, which is of non-class type ‘Factoring()’
Problem1.InitialMessage();
The code for "FactoringProgram.h" is:
#ifndef FactoringProgram_h
#define FactoringProgram_h
#include <stdio.h>
#include <iostream>
class Factoring
{
private:
int m_FirstCoefficent;
char m_FirstOperator;
int m_SecondCoefficent;
char m_SecondOperator;
int m_3rdExpression;
public:
Factoring();
int InitialMessage();
};
#endif
FactoringProgram.cpp code:
#include <stdio.h>
#include <iostream>
#include "FactoringProgramH.h"
int main()
{
Factoring Problem1();
Problem1.InitialMessage();
return 0;
}
FactoringProgram2nd.cpp code:
#include "FactoringProgramH.h"
#include <stdio.h>
#include <iostream>
Factoring::Factoring(int FirstCoefficent=0, char FirstOperator='+',
int SecondCoefficent=1, char SecondOperator='+', int 3rdExpression=1)
: m_FirstCoefficent(FirstCoefficen), m_FirstOperator(FirstOperator),
m_SecondCoefficent(SecondCoefficent), m_SecondOperator(SecondOperator),
m_3rdExpression(3rdExpression);
{
}
int Factoring::InitialMessage()
{
std::cout << "Ok right now your expression is looking like: "
<< FirstCoefficent << "x^2 " << FirstOperator << " " << SecondCoefficent
<< " x" << SecondOperator << " " << 3rdExpression;
}
Your code has several small errors. Here is a version that works (you can compare and see what I had to change). A summary of the changes are:
default parameter values should be in the header file (*.h);
you cannot start variable/argument names with numbers;
int InitialMessage() doesn't return anything, so I changed it to void InitialMessage();
when you initialize fields in a constructor, the last field cannot end with a semi-colon;
fixed the most vexing parsing (per #RSahu comment) in main.cpp.
FactoringProgram.h
#ifndef FactoringProgram_h
#define FactoringProgram_h
#include <stdio.h>
#include <iostream>
class Factoring
{
private:
int m_FirstCoefficent;
char m_FirstOperator;
int m_SecondCoefficent;
char m_SecondOperator;
int m_3rdExpression;
public:
Factoring(int FirstCoefficent = 0, char FirstOperator = '+',
int SecondCoefficent = 1, char SecondOperator = '+', int thirdExpression = 1);
void InitialMessage();
};
#endif
FactoringProgram.cpp
#include "FactoringProgram.h"
Factoring::Factoring(int firstCoefficent, char firstOperator, int SecondCoefficent, char SecondOperator, int thirdExpression) :
m_FirstCoefficent(firstCoefficent),
m_FirstOperator(firstOperator),
m_SecondCoefficent(SecondCoefficent),
m_SecondOperator(SecondOperator),
m_3rdExpression(thirdExpression)
{}
void Factoring::InitialMessage()
{
std::cout << "Ok right now your expression is looking like: "
<< m_FirstCoefficent << "x^2 " << m_FirstOperator << " " << m_SecondCoefficent
<< " x" << m_SecondOperator << " " << m_3rdExpression;
}
main.cpp
#include <stdio.h>
#include <iostream>
#include "FactoringProgram.h"
int main()
{
Factoring Problem1;
Problem1.InitialMessage();
return 0;
}
To this error substitute:
Factoring Problem1();
by:
Factoring Problem1 = Factoring();
The problem is that the compiler is interpreting this line as a function declaration rather than a variable declaration. AS mentioned in the comments, this is known as the most vexing parser problem.
Obs: The code you posted contain many more minor errors.
You should define Factoring() without params and I used headers in FactoringProgram.h
FactoringProgram.h
#include <stdio.h>
#include <iostream>
class Factoring
{
private:
int m_FirstCoefficent;
char m_FirstOperator;
int m_SecondCoefficent;
char m_SecondOperator;
int m_3rdExpression;
public:
Factoring();
Factoring(int,char,int,char,int);
int InitialMessage();
};
#endif
FactoringProgram.cpp
#include "FactoringProgram.h"
int main()
{
Factoring Problem1 = Factoring();
Problem1.InitialMessage();
system("pause");
return 0;
}
FactoringProgram2nd.cpp
#include "FactoringProgram.h"
Factoring::Factoring()
{
*this = Factoring(0, '+', 1, '+', 1);
}
Factoring::Factoring(int FirstCoefficent = 0, char FirstOperator = '+',int SecondCoefficent = 1, char SecondOperator = '+', int _3rdExpression = 1) : m_FirstCoefficent(FirstCoefficent), m_FirstOperator(FirstOperator),m_SecondCoefficent(SecondCoefficent), m_SecondOperator(SecondOperator),m_3rdExpression(_3rdExpression)
{
}
int Factoring::InitialMessage()
{
std::cout << "Ok right now your expression is looking like: "
<< m_FirstCoefficent << "x^2 " << m_FirstOperator << " " << m_SecondCoefficent
<< " x" << m_SecondOperator << " " << m_3rdExpression;
return 0;
}
Something I am working on is making a code that focuses on making a class that reverses an order of numbers. This will then get put into the main code that will eliminate any trailing zeroes. I can't seem to wrap my head around how classes work and where I am going wrong. Here is my code:
Numbers.h
#pragma once
#include <iostream>
class Numbers
{
public:
int digit
private:
void Numbers::reverse();
};
Numbers.cpp
#include "Numbers.h
#include <iostream>
using namespace std;
void Numbers::reverse(){
int n, reversedNumber = 0, remainder;
cout << "Enter the number you would like to manipulate! " << endl;
cin >> n;
while (n !=0)
{
remainder = n % 10;
reversedNumber = reversed Number * 10 + remainder;
n /= 10;
}
//return *this;
}
Main.cpp
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include "Numbers.h"
using namespace std;
int main()
{
Numbers.reverse;
system("pause");
return 0;
}
I can't seem to make the reverse function in my Numbers.cpp work in the main function. I am new to C++ and am not sure where I am going wrong. Any help would be appreciated!
OK, there are a lot of mistakes or learning errors in your code. Your header file should look something like:
#pragma once
class Numbers
{
public:
Numbers();
~Numbers();
int Reverse(int input); // Function is 'public'.
};
Your CPP file will then be (parts taken from S.O. post here):
#include "Numbers.h"
Numbers::Numbers()
{
}
Numbers::~Numbers()
{
}
// No need to store the value in 'digit' since this
// is just an algorithm which can return the result.
int Numbers::Reverse(int input)
{
int ret = 0;
while(input > 0)
{
ret = ret * 10 + (input % 10);
input = input / 10;
}
return ret; // Return the reversed number and let the user decide what to do.
}
Then you can use your class as follows:
#include "Numbers.h"
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number to reverse: ";
cin >> num;
Numbers numClass;
cout << "Reversed number is: " << numClass.Reverse(num) << endl;
return 0;
}
I am getting a linker error undefined reference to Person::Person when trying to implement my program. The three parts are below. I have been working on fixing it for a few hours now. I know it's probably something simple that I am just not seeing. But I have looked around on the internet and still have not found my answer. So any help would be appreciated.
#ifndef PERSON0_H_
#define PERSON0_H_
#include <string>
class Person // class declaration
{
private:
static const int LIMIT = 25;
std::string lname;
char fname[LIMIT];
public:
Person() {lname = ""; fname[0] = '\0';}
Person(const std::string & ln, const char * fn = "Hay you");
void Show() const;
void FormalShow() const;
};
#endif
#include <iostream>
#include <string>
#include "person0.h"
void Person::Show() const
{
using namespace std;
std::cout << fname << " " << lname << '\n';
}
void Person::FormalShow() const
{
using std::cout;
std::cout << lname << ", " << fname << '\n';
}
#include <iostream>
#include <string>
#include "person0.h"
int main()
{
using namespace std;
Person one;
Person two("Smythecraft");
Person three("Dimwiddy", "Sam");
one.Show();
cout << endl;
one.FormalShow();
cout << endl;
two.Show();
cout << endl;
two.FormalShow();
cout << endl;
three.Show();
cout << endl;
three.FormalShow();
cin.get();
cin.get();
return 0;
}
I am not really a C++ person, so the terminology might be wrong, but I would say that the implementation of the
Person::Person(const std::string & ln, const char * fn)
constructor is missing.