且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将整数数组转换为数字

更新时间:2023-01-14 11:53:04

使用 std :: stringstream

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;
    int arr[] = {60, 321, 5};

    for (unsigned i = 0; i < sizeof arr / sizeof arr [0]; ++i)
        ss << arr [i];

    int result;
    ss >> result;
    std::cout << result; //603215
}

请注意,在C ++ 11中,轻微的丑陋循环可以替换为:

Note that in C++11 that mildly ugly loop can be replaced with this:

for (int i : arr)
    ss << i;

此外,看看如何有一个很好的溢出可能性,数字的字符串形式可以使用 ss.str()访问。为了避免溢出,它可能更容易使用,而不是试图把它绑定成一个整数。负值也应该考虑在内,因为这只会在第一个值为负时才起作用(有意义)。

Also, seeing as how there is a good possibility of overflow, the string form of the number can be accessed with ss.str(). To get around overflow, it might be easier working with that than trying to cram it into an integer. Negative values should be taken into consideration, too, as this will only work (and make sense) if the first value is negative.