atoi
在 cstdlib 中
调用了一个最简单的函数: http ://www.cplusplus.com/reference/cstdlib/atoi/
int number = atoi(str.c_str()); // .c_str() is used because atoi is a C function and needs a C string
这些函数的工作方式如下:
int sum = 0;
foreach(character; string) {
sum *= 10; // since we're going left to right, if you do this step by step, you'll see we read the ten's place first...
if(character < '0' || character > '9')
return 0; // invalid character, signal error somehow
sum += character - '0'; // individual character to string, works because the ascii vales for 0-9 are consecutive
}
如果您给出“23”,则为 0 * 10 = 0。0 + '2' - '0' = 2。
下一个循环迭代:2 * 10 = 20。20 + '3' - '0' = 23
完毕!