how to convert an int to a char C++

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

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; }

回答1:

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.



回答2:

Assuming you want to manually convert each char into an int, here is a very rough idea. Use a switch statement to convert each char into its ascii value. For example, switch(char_to_convert)'s case 38 would return 1. Basically, "1" converted to ASCII is 49(Thank you Ben Voigt for the correction). You don't actually need to convert it; you compiler will notice and convert it for you. Then you make the comparisons. See Ascii Table for a complete list.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!