将数组元素复制到结构 [英] Copying Array elements to a Structure

查看:72
本文介绍了将数组元素复制到结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!
我必须将字符串数组的元素复制到结构中.

我的数组声明如下:
irr::core::array<irr::core:stringc> result:;

我的结构声明如下:

Hi!
I''ve to copy elements of a string array to a Structure.

My array is declared as follows:
irr::core::array<irr::core:stringc> result:;

My Structure is declared as follows:

struct playerData
{
 int id,matches,innings,notouts,runs,highest,hundred,fifty,catches,strikerate,balls,runs_given,wickets,fivewkt;
    char bestbowling[32];
};



如何将数组元素复制到结构元素?



How to copy the array elements to the structure elements?

推荐答案

由于我不知道数组具有什么接口,字符串从数组中出来的顺序如何我将假设您的字符串是std :: string,而您的数组是std :: vector< std :: string xmlns:std =#unknown">.

首先要做的是为您的结构构造一个构造函数:

As I''ve no idea what interface your array has and what order the strings come out of the array I''m going to assume that your strings are std::string and your array is std::vector<std::string xmlns:std="#unknown">.

The first thing to do is give your structure a constructor:

playerData::playerData( const std::vector<std::string> &input )
{
}



完成此操作后,问题便是将字符串转换为整数.为此编写一个函数:



Once you''ve done that the problem is to convert a string to an integer. Write a function for that:

int string_to_int( const std::string &str )
{
    int value = 0;
    std::istringstream in_str( str );
    in_str >> value;
    if( !in_str )
    {
        throw std::runtime_error( "Couldn''t convert string to integer" );
    }
}



最后根据该函数实现构造函数:



and finally implement your constructor in terms of that function:

playerData::playerData( const std::vector<std::string> &input ) : 
    id( string_to_int( input[ 0 ] ) ),
    matches( string_to_int( input[ 1 ] ) ),
    // etc, one initialisation per member
{
}



干杯,



PS:这在某些方面尤其容易造成人为伤害.我很想做的是从流中实现一个构造函数,并像这样传递数据.测试起来更容易,您也可以从命令行输入玩家数据.



Cheers,

Ash

PS: This is particularly braindamaged in some respects. What I''d be tempted to do would be to implement a constructor from a stream and pass the data in like that. It''d be easier to test and you could enter player data from the command line as well.


您在
What was wrong with the answers you got in the forum[^]?

And why did you remove that message? There is no point in asking questions if you don''t even bother trying to understand the answers.


这篇关于将数组元素复制到结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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