C++数组:包含类型的转换

2 c++ arrays

在C++中将固定长度字符串数组转换为固定长度整数数组的最佳方法是什么?

luk*_*uke 10

这会将一个字符数组复制到一个int数组中:

#include <algorithm>
char foo[9] = "asdfasdf";
int bar[9];
std::copy(foo, foo+9, bar);
Run Code Online (Sandbox Code Playgroud)

性病::复制

这将空终止字符数组{'a','s','d','f','a','s','d','f','\ 0'}的值分配给整数数组,产生{97,115,100,102,97,115,100,102,0}.请注意,这包括原始字符串的空终止.


这将解析一个字符串数组,并将它们的整数值放入一个int数组中:

#include <algorithm>
#include <sstream>
#include <string>

template <class T>
T parse(const std::string& str)
{
    T temp;
    std::istringstream iss(str);
    iss >> temp;
    if(iss.bad() || iss.fail())
    {
        // handle conversion failure
    }
    return temp;
}

...

std::string foo[3];
int bar[3];
foo[0] = "67";
foo[1] = "11";
foo[2] = "42";

std::transform(foo, foo+3, bar, parse<int>);
Run Code Online (Sandbox Code Playgroud)

的std ::变换

这会将数组foo中的每个字符串转换为整数,并将它们放在int,bar数组中.


jal*_*alf 6

#include <algorithm>

std::string foo[9];
int bar[9];

std::transform(foo, foo+9, bar, MyMagicStringToIntFunction);
Run Code Online (Sandbox Code Playgroud)

MyMagicStringToIntFunction是您希望用于将字符串转换为整数的函数.既然你没有说明你想要怎么做,我就无法回答那个部分.

这是我对你想做什么的猜测,但是更多的信息会有所帮助.("字符串数组是指一个std :: strings数组?你想如何执行转换?"

无论如何,std :: transform是我最好的,但你必须自己填补空白.