在2个不同的结构中分配2个字符串:: Array

时间:2017-12-26 22:57:29

标签: c++ arrays string struct

这是第一个结构并包含第一个成员

#include <iostream>
#include <algorithm>
#include <cstring>
struct Student_Data {
    string Assignment[200];
};

这是第二个结构并包含一个成员

struct Courseassign { 
    string createassig[200];
};

//here is declare function 
Doc(Student_Data ,Courseassign );
//the main function to declare 2 structures and call the Doc() function 
int main()
{
    Courseassign phase1 ; // declare 1st struct 
    Student_Data Student_Details ; // declare 1st struct 
    Doc(  phase1  , Student_Details); // Call Doc() function to run it
}

这是我们的功能,我已经尝试使用copy(),但它也没有工作,我知道cpy应该是char而不是字符串所以我只想让成员等于另一个成员使用字符串数组

时的另一个结构
void Doc(Courseassign phase1, Student_Data Student_Details )
{
    for(int i=0;i<200;i++) {
        cout<< "create assign " << endl ; 
        cin >> phase1.createassig[i]  ; // here to enter member value 
        // here it's just a try to make them equal each other but it failed
        Student_Details.Assignment[i] = phase1.createassig[i];
        // here it should be Array of char but i need to Array of strings so what should i use
        cpy( Student_Details.Assignment[i],phase1.createassig[i]); 
    }
}

1 个答案:

答案 0 :(得分:0)

尝试时会出现什么错误:Student_Details.Assignment[i] = phase1.createassig[i];

strcpy正如您所提到的那样是char* s,如果您想将一个字符串值分配给另一个字符串变量,您还可以使用string::assign

例如,在您的情况下,它将是:

Student_Details.Assignment[i].assign( phase1.createassig[i] );

最后,正如@Peter的评论中所提到的,你是按值传递你的结构,所以你在其中所做的任何更改都不会传播给传递给函数的实际结果。将在本地对它们进行更改,并在函数终止时销毁。您可以尝试通过引用传递结构,即

void Doc(Courseassign&, Student_Data&);