Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert an int to a char C++

Tags:

c++

Im having trouble with an assignment where I have to convert three variables of a clock (int hour, int minutes, and bool afternoon) to be converted to a string in a method. I tried converting the int to a char and then replacing each string with the char. The function is suppose to return T/F if the conversion worked or not. Here is what I have so far:

class Time
{
private:
  int hour;
  int minutes;
  bool afternoon;
public:
  void setHour(int hr);
  void setMinutes(int min);
  void setAfternoon(bool aft);

  int getHour();
  int getMinutes();
  bool getAfternoon();

  bool setAsString(string time);
  string getAsString();

  Time(void);
  ~Time(void);
};

and

bool Time::setAsString(string time){
char min = minutes;
char hr = hour;

char hr[0] = time[0];
char hr[1]= time[1];
char min[0] = time[3];
char min[1] = time[4];
char afternoon = time[6];
if ((hourTens > 1) || (minTens > 5)) {
return false;
} else {
return true;
}
}
string Time::getAsString(){
return false;
}
like image 838
M_and_o Avatar asked Jan 13 '23 11:01

M_and_o


1 Answers

it is straight-forward in fact, but may involve a little twist in mind at first.

I am not going to give you the actual code, but some snippet that, if you can understand them, you should be able to solve the problem by yourself:

What you want to do is converting an integer to a string/char. The most basic thing you need to do is to convert a single digit int to corresponding char.

// for example you have such integer
int i = 3;

// and you want to convert it to a char so that
char c = '3';

what you need to do is, by adding i to '0'. The reason why it works is because '0' actually means an integer value of 48. '1'..'9' means 49..57. This is a simple addition to find out corresponding character for an single decimal digit integer:

i.e. char c = '0' + i;

If you know how to convert a single decimal digit int to char, what's left is how you can extract individual digit from a more-than-one-decimal-digit integer

it is simply a simple math by making use of / and %

int i = 123 % 10;  // give u last digit, which is 3
int j = 123 / 10;  // give remove the last digit, which is 12

The logic left is the homework you need to do then.

like image 180
Adrian Shum Avatar answered Jan 21 '23 14:01

Adrian Shum