How to convert int to char C ++

I am having problems with assignment, where I need to convert three variable numbers of hours (int hour, int minutes and bool day) to convert to a string in a method. I tried to convert int to char and then replace each line with char. The function should return T / F if the conversion worked or not. Here is what I still have:

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; } 
+4
source share
2 answers

this is straightforward, but may include a slight twist first.

I am not going to give you the actual code, but some piece that, if you can understand them, you have to solve this problem yourself:

What you want to do is convert the integer to the string / char. The most important thing you need to do is convert one int digit to the 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 by adding me to '0'. The reason this works is because '0' actually means an integer value of 48. '1' .. '9' means 49..57. This is a simple addition to define the appropriate character for an integer with a decimal digit:

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

If you know how to convert one decimal int to char, then what remains is how you can extract a single digit from integers with more than one decimal.

it's just simple math using / 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 on the left is the homework you need to do.

+5
source

Assuming you want to manually convert each char to int, here is a very rough idea. Use the switch to convert each char to its ascii value. For example, switch(char_to_convert) case 38 will return 1. Basically, "1" converted to ASCII is 49 (Thanks, Ben Weigt for the fix). In fact, you do not need to convert it; you compiler will notice and convert it for you. Then you do the comparisons. See Table Ascii for a complete list.

0
source

Source: https://habr.com/ru/post/1478894/


All Articles