将字符串元素转换为整数C ++

时间:2014-02-24 00:51:02

标签: c++ string integer

我有一串数字,我想将这些数字相乘

string myS = "731671765313";
int product = 1;
    for(int i = 0; i<myS.length(); i++)
        product *= myS[i];

如何将字符串元素转换为int,因为结果完全错误。 我尝试将其转换为 int 但是徒劳无功。

1 个答案:

答案 0 :(得分:4)

使用std::accumulate(因为您正在累积元素的乘积,因此它使意图清晰)并回想'0'不是0,而是数字字符是连续的。例如,在ASCII中,'0'为48,'1'为49,等等。因此,减去'0'会将该字符(如果是数字)转换为适当的数值。

int product = std::accumulate(std::begin(s), std::end(s), 1, 
    [](int total, char c) {return total * (c - '0');}
);

如果你不能使用C ++ 11,它很容易被替换:

int multiplyCharacterDigit(int total, char c) {
    return total * (c - '0');
}

...

int product = std::accumulate(s.begin(), s.end(), 1, multiplyCharacterDigit);

如果这些都不是一个选项,那么你所拥有的几乎就在那里:

int product = 1;
    for(int i = 0; i<myS.length(); i++)
        product *= (myS[i] - '0');
相关问题