New guy is here again and i got stuck again as usual. (Dunno what my question title should be but its definitely related to function i think) I wanted to make the user roll a dice and max out when they reach 20. But the thing is my function obj.currentRoll();
is not adding up the previous rolls as i intended it to. Basically i wanted it to store the value value=value+roll;
for consecutive turns so that later on i could use an if statement like if (value>max){return 0}
or sth like that. I was able to do it in a easier way without using seperate class or functions but I hoped to achieve the same result this way too and failed. Any suggestions?
#include <iostream>
#include "myClass.h"
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(0));
std::string rollCh;
const int max=20;
std::cout<<"Your lucky number for the day is " <<1+(rand()%30)<<"\n";
std::cout<<"Roll the dice? (Y/N)"<< "\n";
std::string ch;
std::cin>>ch;
if(ch=="Y"||ch=="y"){
myClass obj;
do
{
std::cout<<"Rolling...\n"<<"\n";
std::cout<<"You rolled "; obj.funcRoll();std::cout<<"!!!" <<"\n";
std::cout<<"Double checking your roll...yes it is ";obj.funcRoll();
obj.currentRoll();
std::cout<<"\n\n Roll again? (Y/N)"<<"\n";
std::cin>>rollCh;
}
while (rollCh=="Y"||rollCh=="y");
}
return 0;
}
myClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
class myClass
{
public:
myClass();
void funcRoll();
int roll;
int value;
void currentRoll();
};
#endif // MYCLASS_H
myClass.cpp
#include "myClass.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
myClass::myClass()
{}
void myClass:: funcRoll(){
srand(time(0));
roll=1+(rand()%6);
std::cout<<roll;
}
void myClass:: currentRoll(){
value=0;
value=value+roll;
std::cout<<"\n You have rolled "<< value<<" so far";
}
Easier way which i did first
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
int max=20;
int value=0;
int roll;
std::string ch;
do
{
srand(time(0));
roll=1+(rand()%6);
std::cout<<"\nYou rolled "<<roll<<"\n";
value=value+roll;
std::cout<<"Your total value = " << value<<"\n";
if (value<max){
std::cout<<"continue? \n\n"<<"\n";
std::cin>>ch;}
else {
std::cout<<"You have maxed out. Congrats!"<<"\n";
return 0;
}
}
while (ch=="y"||ch=="Y");
return 0;
}