将字符串元素转换为整数C ++ [英] Convert string element to integer C++

查看:116
本文介绍了将字符串元素转换为整数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字串,我想要乘以这些数字

i have a string of numbers, and i want to multiply these numbers

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

如何将字符串元素转换为int,因为结果是完全错误的。

How to convert the string element to int because the result is totally wrong. I tried casting it to int but in vain.

推荐答案

使用 std :: accumulate (因为你正在积累一个元素的产物,所以它的意图是清楚的),并回想一下'0'不是0,但是数字字符是连续的。例如,在ASCII中,'0'为48,'1'为49等。因此, code>'0'会将该字符(如果是数字)转换为适当的数值。

Use std::accumulate (because you're accumulating a product of elements, so it makes the intent clear) and recall that '0' is not 0, but that the digit characters are contiguous. For example, in ASCII, '0' is 48, '1' is 49, etc. Therefore, subtracting '0' will convert that character (if it's a digit) to the appropriate numerical value.

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

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

If you can't use C++11, it's easily replaced:

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

...

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

如果这两个选项都不是选项,您所拥有的几乎是:

If neither of those are an option, what you had is almost there:

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

这篇关于将字符串元素转换为整数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆