【问题标题】:Assigning 2 string::Array in 2 different a struct在 2 个不同的结构中分配 2 个 string::Array
【发布时间】:2017-12-26 22:57:29
【问题描述】:

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

#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]); 
    }
}

【问题讨论】:

  • 你真的应该清理你的代码块。它的可读性不是很强,而且那里的 cmets 没有注释。请阅读the MCVE section,因为当我无法编译和运行您的代码时,很难提供帮助。我也不确定出了什么问题,因为你还没有告诉我们什么是行不通的。它是否正在编译但运行不正确?你得到一个编译错误?我可以看到一个明显的问题是您通过值传递phase1Student_Details,而不是引用,因此它们被复制进来;您无法从内部更改原件。
  • @Taywee 代码没问题,它正在运行,但是使成员彼此相等的功能不起作用,在插入 phase1.createassig[i] 后,我只想制作 Student_Details.Assignment[ i] 等于在摘要中插入的值:问题是如何将字符串数组的值分配(如另一个中的推送值)字符串数组的值到另一个字符串数组
  • 不要使用数组,使用 std::vector。
  • 在这种情况下,数组很好。通过引用而不是值传递(您的签名应该更像void Doc(Courseassign &amp;phase1, Student_Data &amp;Student_Details))。您的代码正在复制您的对象,然后在函数结束时丢弃副本。不过,我不确定这里的目标是什么,或者 Courseassign 的意义是什么,因为它看起来根本没有被使用。
  • @Taywee 非常感谢它的工作原理和此代码的目标它是 myproject 的一部分(顺便说一句,它是第一个项目),它是学生和医生的教育系统项目(它只是培训)

标签: c++ arrays string struct


【解决方案1】:

您尝试时遇到什么错误:Student_Details.Assignment[i] = phase1.createassig[i];

你提到的strcpychar*s,如果你想将一个字符串值分配给另一个字符串变量,你也可以使用string::assign

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

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

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

void Doc(Courseassign&, Student_Data&);

【讨论】:

  • 谢谢,我可以使用 string::assign 而不通过引用传递参数
猜你喜欢
  • 2021-07-01
  • 2021-11-15
  • 2023-03-24
  • 1970-01-01
  • 2017-12-19
  • 2021-07-25
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
相关资源
最近更新 更多