You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何理解C++字符串转long函数的实现逻辑及关键细节?

#include <iostream>
#include <cstring>

using namespace std;

long digitToLong(char c) { // function returns the value type long (c - '0') and takes the char c as an argument. 
    return c - '0';  // c is equal to (text[i]) and 0 is the code ascii assigned as a nr 0.
}

long toLong(string text) { /* takes a text that represents a number and then transfers the text into a number.*/
    long result = 0;  

    for (int i = 0; i < text.length(); i++) { /* for loop that iterates through every character included in a text length.*/
        result *= 10;  
        result += digitToLong(text[i]); 
    }

    return result;
}


int main() {
    char number[] = "0123456789";

    cout << (toLong("0") == 0) << endl; 
    cout << (toLong("1") == 1) << endl;
    cout << (toLong("2") == 2) << endl;
    cout << (toLong("5") == 5) << endl;
    cout << (toLong("12") == 12) << endl;
    cout << (toLong("123") == 123) << endl;
    cout << (toLong("12345") == 12345) << endl;
}

问题求助

上述代码为老师采用的字符串转long类型实现方案,通过ASCII值转换获取数字字符对应的数值。我在理解该转换过程时遇到两处困惑:

  1. 代码中的result *= 10;与result += digitToLong(text[i]);是否可改写为result = result * 10 + (c - '0')?为何需要将result乘以10?我推测这与十进制数位左移有关,但不清楚代码中的实际运行机制。
  2. 代码中变量c具体被赋值为哪部分内容?是否等于text[i]?text[i]代表循环迭代中的什么?该如何理解这部分遍历逻辑?

问题解答

问题1

完全可以改写成result = result * 10 + (text[i] - '0'),两行代码和合并后的一行逻辑完全等价,只是写法不同。

至于为什么要给result乘10,用实际例子看最直观:比如转换字符串"123",循环过程是这样的:

  • 初始result = 0
  • 第一次循环(i=0,字符是'1'):result *=10后还是0,再加1,result变成1
  • 第二次循环(i=1,字符是'2'):result *=10变成10(相当于把之前的1从个位挪到十位),再加2,result变成12
  • 第三次循环(i=2,字符是'3'):result *=10变成120(把12从个位+十位挪到十位+百位),再加3,result变成123
    简单说就是每读一个新数字,就把之前拼好的数往十进制高位挪一位(挪一位就是乘10),再把新数字放到个位,逐步拼接出完整的数值。

问题2

代码里的c是digitToLong函数的参数,每次调用这个函数时传入的是text[i],所以c就是当前循环到的text[i]。

text是要转换的数字字符串,text[i]代表字符串中第i个位置的字符(字符串下标从0开始):

  • 比如转换"123"时,i=0对应'1',i=1对应'2',i=2对应'3'
    循环从i=0开始,直到i小于字符串长度,这样就能逐个遍历字符串里的所有数字字符,把每个字符转成对应的数值后拼到结果里。

内容的提问来源于stack exchange,提问作者Marika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 06:52:50