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;
}
Related
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.
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 :)
I'm working on C++, and this is just a very basic program, but I'm still getting an error.
The error message is:
'class secondary' has no member named 'getting'.
Why is this? It works for my void setting, but not for getting? What am I doing wrong here?
main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
string getting();
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if(factor < 3){
result = "You have a very low self esteem.";
}elseif(factor > 3){
if(factor > 7){
result = "You have a very high self esteem."
}else{
result = "You have a medium self esteem."
}
}
return result;
}
private factor;
Actually, looking at this again, and deeper, this code has many issues (semicolons missing at key points and the private int definition should have been in the header file, not the cpp file 9t(private is its own section, see below):The problem, from what I can see, s has not yet been instantiated yet, do so and the operation should work correctly.
Please also note that when factor was defined in the cpp file, it was defined at bottom, it should actually be defined before any use of the variable to be defined (in the header file is better meet with common/conventional coding standards).
Please check this tested code:
main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
std::string getting();
private: // Note: this is how you do private
int factor; // This is the definition with type int, missing in original
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if (factor < 3){
result = "You have a very low self esteem.";
}else if(factor > 3){
if (factor > 7){
result = "You have a very high self esteem.";
}
else{
result = "You have a medium self esteem.";
}
}
return result;
}
When I input two integers, the output is correctly their difference. However when I enter a string and a char, instead of returning how many times the char appears in the string, it returns -1, which is the out put for error. Could anyone please help me? It's just my second day learing c++...
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s[])
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s[0],1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
if(std::cin>> c[200] >> d){
mycount(a,b);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
Hint - what will this program print?
#include <iostream>
using namespace std;
int main()
{
char c[200],d;
cout << sizeof(c) << endl;
cout << sizeof(d) << endl;
return 0;
}
Answer:
200
1
That declaration does not do what you think it does - c is an array of 200 chars, d is a single char. It's a feature of the C declaration syntax, same as:
int *c, d;
c is a pointer to int, d is an int.
Since you are doing C++, why not make your life easier and use std::string instead?
A few changes should fix your problems. First when inputting an array with cin use getline and call ignore right before hand. I find it easier to pass s as a char instead of an array of size one make sure your call your second my count with c and d instead of a and b.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s)
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s,1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
std::cin.ignore();
if(std::cin.getline (c,200) && std::cin >> d){
mycount(c,d);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
These changes should fix it.
I am passing a streamstring from one random generator to another to keep track of the current state of an engine (boost random library). It allows me stop at any point and save the current state to reproduce a series later on in the code or continue it.
It works fine until I use different random generators while passing the same stringstream (as reproduce bellow). I cannot use different streams for the two, as in the real example a class will call to different distributions in a random order...
#ifndef RANDOM_HPP
#define RANDOM_HPP
namespace RandomG{
using namespace std;
using namespace boost::random;
int getSeed()
{
ifstream rand("/dev/urandom");
char tmp[sizeof(int)];
rand.read(tmp,sizeof(int));
rand.close();
int* number = reinterpret_cast<int*>(tmp);
return (*number);
}
void Get_Rstream(stringstream &s)
{
mt19937 randgen(getSeed());
s.clear();
s << randgen;
}
template<class distribution>
class Random
{
public:
Random(distribution nd)
{
mt19937 randgen(getSeed());
rng=new variate_generator<mt19937,distribution >(randgen, nd);
}
virtual ~Random()
{
delete rng;
}
void reset(void)
{
(*rng).distribution().reset();
}
double operator()(stringstream &s)
{
double x;
s >> (*rng).engine();
x=(*rng)();
return x;
}
variate_generator<mt19937,distribution > *rng;
};
}
#endif
So now if I instantiate two instances of these classes (below its two uniform but it could be a uniform and a Gaussian or anything else and could be called in a random order).
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include "Random.hpp"
using namespace boost::random;
using namespace std;
int main()
{
int M=20;
stringstream ss;
RandomG::Get_Rstream(ss);
string ss2=ss.str();
stringstream ss3;
ss3.clear();
ss3.str(ss.str());
boost::random::uniform_01<> N;
RandomG::Random<boost::random::uniform_01<> > *unif_rand1= new RandomG::Random<boost::random::uniform_01<> >(N);
boost::random::uniform_01<> U;
RandomG::Random<boost::random::uniform_01<> > *unif_rand2=new RandomG::Random<boost::random::uniform_01<> >(U);
(*unif_rand1).reset();
(*unif_rand2).reset();
for(int i=0;i<M;i++)
{
cout << (*unif_rand1)(ss) << " ";
}
for(int i=0;i<M;i++)
{
cout << (*unif_rand2)(ss) << " ";
}
cout <<"\\\\\\\\\\\\\\\\\\\\"<<"\n";
(*unif_rand1).reset();
(*unif_rand2).reset();
for(int i=0;i<M;i++)
{
cout << (*unif_rand1)(ss3) << " ";
}
for(int i=0;i<M;i++)
{
cout << (*unif_rand2)(ss3) << " ";
}
return 0;
}
This should give me two series of the same random numbers, but instead gives me the same random numbers for unif_rand1 but not for unif_rand2.
From what I understood feeding the same state to two different random number generator should give the same result or is there some way to reset them between draws ?
results:
0.525384 0.038626 0.563798 0.705042 0.725001 0.311586 0.843047 0.606338 0.163695 0.437574 \\\\\\\\\\
0.525384 0.038626 0.563798 0.705042 0.725001 0.0566288 0.93966 0.417343 0.686245 0.84118
Thanks for any responses or advises
(the code should be reproducible under linux).