0

运算符 int() 函数将字符串转换为 int

class mystring
{ 
  private:
    chat str[20];

  public:
   operator int()             // i'm assuming this converts a string to an int
   {
     int i=0,l,ss=0,k=1;

     l = strlen(str)-1;
     while(l>=0)
     {
       ss=ss+(str[l]-48)*k;
       l--;
       k*=10;
     }
     return(ss);
   } 
}

int main()
{
  mystring s2("123");
  int i=int(s2);
  cout << endl << "i= "<<i;
}

那么背后的逻辑是operator int()什么?里面的48是什么?有人可以向我解释从字符串转换为 int 背后的算法吗?

4

3 回答 3

3

Yes this converts a string to an integer. 48 is the ASCII value for '0'. If you subtract 48 from an ASCII digit you'll get the value of the digit (ex: '0' - 48 = 0, '1' - 48 = 1, ..). For each digit, your code calculates the correct power of 10 by using k (ranges between 1...10^{ log of the number represented by the input string}).

于 2012-04-13T16:49:22.183 回答
1

It does indeed convert a string to an integer. The routine assumes that all characters are decimal digits (things like minus sign, space, or comma will mess it up).

It starts with the ones place and moves through the string. For each digit, it subtracts off the ASCII value of '0', and multiplies by the current place value.

于 2012-04-13T16:48:06.353 回答
0

这确实将字符串转换为整数。如果您查看 ascii 表,数字从值 48 开始。使用此逻辑(假设字符串“123”),while 循环将执行以下操作:

l=2

ss=0+(51-48)*1

所以在这种情况下 ss = 3

下一个循环我们得到

l=1

ss=3+(50-48)*10 

所以 ss = 23

下一个循环

l=0
ss=23+(49-48)*100

所以 ss = 123

循环中断,我们返回一个值 123 的整数。

希望这可以帮助!

于 2012-04-13T16:52:41.843 回答