将结构的成员复制到另一个结构
copying members of structure to another structure
我正试图将成员从一个结构复制到另一个结构,但我不知道如何做到这一点。
struct StudentTxt
{
int ID;
string lname;
string fname;
string initial;
int age;
double balance;
};
struct StudentBin
{
int ID;
int age;
double balance;
char fullname[50];
};
我读取文件并将所有数据存储到第一个结构中,然后将lname、fname和initial组合成一个字符串。
问题是,我试图将字符串复制到第二个结构中的全名,以及ID、age、Balance。
有人能指引我走正确的路吗。
任何帮助都将不胜感激。
写一个函数来执行翻译和复制怎么样?
void studentCopy( StudentTxt const * pSrc, StudentBin * pDst ) {
pDst->ID = pSrc->ID;
pDst->age= pSrc->age;
pDst->balance = pSrc->balance;
string const name = pSrc->fname + pSrc->initial + pSrc->lname;
size_t const dstLen = sizeof( pDst->fullname );
strncpy( & pDst->fullname, name.c_str(), dstLen );
pDst->fullname[ dstLen - 1 ] = 0; // NUL terminate
}
为什么不能只使用赋值运算符?
// Say these are for the same student
StudentTxt studentATxt;
StudentBin studentABin;
// Copy items over
StudentABin.ID = StudentATxt.ID;
StudentABin.age = StudentATxt.age;
StudentBin.fullname = StudentTxt.fname.c_str()
etc
u只需将全名声明为std::string
,然后在转换时写入fullname= lname+ " "+fname+" "+initial;
。
如果必须使用char数组,则执行以下操作:
strcat(fullname,lname.c_str());
strcat(fullname,fname.c_str());
strcat(fullname,initial.c_str());
在进行上述操作之前,请记住使用fullname[0]=0;
初始化全名。您也可以在每次串联后使用strcat(fullname," ");
以获得正确的格式。
然后简单地将第一个结构的其他属性复制到第二个结构中。
对于fullname
部分:
std::string fullname(
StudentATxt.lname + " " +
StudentATxt.fname + " " +
StudentATxt.initial);
if(fullname.size() < 50)
strcpy(StudentABin.fullname, fullname.c_str());
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- std::transform 将一个结构数组复制到另一个结构数组
- C++将结构复制到另一个程序的资源
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 可以访问一个类中的播放器结构,但不能访问另一个类中的播放器结构
- 如何在另一个结构中初始化结构数组?
- 在另一个结构中声明内部结构会导致错误:结构使用无效
- 通过 C++ 中的另一个结构成员访问结构
- 难以从另一个结构中的函数返回结构
- 有没有办法将一个对象注入到另一个对象的结构中?
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 将一个结构的值复制到另一个结构
- 结构C++可以用 0 初始化,但不能用另一个 int 初始化
- 如何将矢量结构从一个标头文件传递到另一个标头文件中的类
- 是否可以定义一个在外部"C"块中继承另一个结构的结构?