简体   繁体   English

如何将字符串数组复制到结构体

[英]How to copy an array of strings to a struct

How can I copy the contents of an array of strings to a struct?如何将字符串数组的内容复制到结构中? Getting error that it cannot convert type string to type string.得到它不能将类型字符串转换为类型字符串的错误。 The last loop is where I am having trouble.最后一个循环是我遇到麻烦的地方。 Do I need to allocate space on the heap for the string array too?我是否也需要在堆上为字符串数组分配空间? I allocated it for the scores.我把它分配给分数。 I thought a string was really an array of characters so I am confused how to use pointers to reference and transfer them.我认为一个字符串实际上是一个字符数组,所以我很困惑如何使用指针来引用和传输它们。

    #include <iostream>
    #include <iomanip>
    #include <string>
    using namespace std;

    struct StudentRecords
    {
     string* namesRec;
     int** examsptr;
     };


    void main()
    {


const int NG = 4;

string names[] = { "Amy Adams", "Bob Barr", "Carla Carr",
                     "Dan Dobbs", "Elena Evans" };

int exams[][NG] = 
{ 
    { 98,87,93,88 },
    { 78,86,82,91 },
    { 66,71,85,94 },
    { 72,63,77,69 },
    { 91,83,76,60 }
};

string *nameHolder = nullptr;


StudentRecords *data = new StudentRecords();
data->examsptr = new int*[NG];

for (int i = 0; i < NG; ++i) 
{
    data->examsptr[i] = new int[NG];
}

for (int count = 0; count < NG; count++)
{
    for (int count2 = 0; count2 < NG; count2++)
        {
         (*data).examsptr[count][count2] = exams[count][count2];
         cout << (*data).examsptr[count][count2] << "         " << exams[count][count2] << endl;
        }
     }

    for (int count3 = 0; count3 < 5; count3++)
    {
   *nameHolder = names[count3];
   (*data).namesRec[count3] = *nameHolder;
    cout << (*data).namesRec[count3] << endl;
     }

You must initialize data->namesRec = new string[size];你必须初始化data->namesRec = new string[size]; because is pointer!!因为是指针!!

Don't use raw pointers to represent arrays.不要使用原始指针来表示数组。

Don't try to manage new and delete on your own, it's just error prone as proven from your code in question.不要尝试自己管理newdelete ,正如您的代码所证明的那样,它很容易出错。

Use the appropriate container classes like std::vector , or smart pointers provided by the c++ standard class library instead.改用适当的容器类,如std::vector或由 c++ 标准类库提供的智能指针

If your professor or TA denies to do so, just leave the course, they're not teaching c++.如果您的教授或助教拒绝这样做,请离开课程,他们不是在教 C++。

try this code:试试这个代码:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

struct StudentRecords
{
    char* namesRec;
    int** examsptr;
};


void main(void)
{
    const int NG = 4;

    char *names[] = { "Amy Adams", "Bob Barr", "Carla Carr",
                        "Dan Dobbs", "Elena Evans" };

    int exams[][NG] = 
    { 
        { 98,87,93,88 },
        { 78,86,82,91 },
        { 66,71,85,94 },
        { 72,63,77,69 },
        { 91,83,76,60 },
    };

    char *nameHolder = nullptr;
    nameHolder = (char*)malloc(50*sizeof(char));

    struct StudentRecords *data = new StudentRecords();
    data->examsptr = new int*[NG];

    for (int i = 0; i < NG; i++) 
    {
        data->examsptr[i] = new int[NG];
    }

    for (int count = 0; count < NG; count++)
    {
        for (int count2 = 0; count2 < NG; count2++)
        {
            data->examsptr[count][count2] = exams[count][count2];
            printf("%d ",data->examsptr[count][count2]);
        }
        printf("\n");
    }
    printf("\n");
    for (int count3 = 0; count3 < 5; count3++)
    {
        strcpy(nameHolder,names[count3]);
        data->namesRec = (char*)malloc(30*sizeof(char));
        strcpy(data->namesRec,names[count3]);
        printf("%s ",data->namesRec);
        free(data->namesRec);
    }

    for (int i = 0; i < NG;i++) 
    {
        delete data->examsptr[i];
    }
    delete data;
    free(nameHolder);
}

Just an hint:只是一个提示:

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

struct Student {
    std::string name;
    std::vector<int> exams;
};


int main() {
    std::vector<Student> sList{ {"Amy Adams",   { 98,87,93,88 }},
                                {"Bob Barr",    { 78,86,82,91 }},
                                {"Carla Carr",  { 66,71,85,94 }},
                                {"Dan Dobbs",   { 72,63,77,69 }}};

    std::string sname = "Elena Evans";    // Just arrived...
    int exms[] = { 91,83,76,60 };         // if you need to use an array
    sList.push_back(Student{sname, {exms,exms+sizeof(exms)/sizeof(int)}}); 

    // show students
    for ( auto & s : sList ) {       // for every element of the vector
        std::cout << s.name << ": \t";
        for ( auto & e : s.exams ) std::cout << e << "  ";
        std::cout << std::endl;
    }

    return 0;
}

If you are not allowed for some reason to use standard library containers and facilities you can at least try to mimic their capabilities and write some functions to manage the copies, allocations and deallocations:如果由于某种原因不允许您使用标准库容器和设施,您至少可以尝试模仿它们的功能并编写一些函数来管理副本、分配和释放:

std::string * _AllocNames( size_t n ) {
    std::string * new_ptr;
    try {
        new_ptr = new std::string[n];
        return new_ptr;
    }
    catch (std::bad_alloc &ba) {       // Something bad happened
        std::cerr << "Error, exception caught: " << ba.what() << '\n';
        exit(1);
    }
}

void _DeAllocNames( std::string * names ) {
    if ( names ) {
        for (size_t i = 0; i < nStd; i++) names[i].clear();
        delete[] names;
    }
}

int ** _AllocExams( size_t n, size_t m ) {
    int ** new_ptr;
    try {
         new_ptr = new int*[n];
         for ( size_t i = 0; i < n; i++ ) new_ptr[i] = new int[m];
         return new_ptr;
    }
    catch (std::bad_alloc &ba) {       // Something bad happened
         std::cerr << "Error, exception caught: " << ba.what() << '\n';
         exit(1);
    }
}


void _DeAllocExams( int ** exams ) {
     if ( exams ) {
         for (size_t i = 0; i < nStd; i++) delete[] exams[i];
         delete[] exams;
     }
}

For the copy you need to remember that an int** isn't the same thing as a int[][4].对于副本,您需要记住 int** 与 int[][4] 不同。

void _Copy( const std::string * source, size_t n, std::string * dest) {
    for ( size_t i = 0; i < n ; i++ ) dest[i] = source[i];  
}

template < size_t K >
    void _Copy( const int source[][K], size_t n, int ** dest) {
        for ( size_t i = 0; i < n ; i++ )
            for ( size_t j = 0; j < K; j++ )
                dest[i][j] = source[i][j];
}

void _Copy( int ** source, size_t n, size_t m, int ** dest) {
        for ( size_t i = 0; i < n ; i++ )
            for ( size_t j = 0; j < m; j++ )
                dest[i][j] = source[i][j];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM