使用字符串函数将文件中的数据读入结构?

Reading in data from a file into a structure using string functions?

我有一个文本文件,我想使用 C++ 字符串函数将数据读入结构。文本文件如下所示。

Thor;3.4;3.21;2.83;3.78
Loki;2.89;2.21;2.10;3.33
Sam;3.65;3.78;4.0;3.89
Olivia;2.36;2.75;3.12;3.33
Bruce;3.12;2.4;2.78;3.2

我有一个 Student 结构数组

struct Student
{
    string name;
    double gpa[4];
};

通过在我的一个函数中执行此操作,我成功地读取了所有数据。

for (int counter = 0; counter < numofStudents; counter++)
{
    getline(infile, pointer[counter].name, ';');

    for (int i = 0; i < 4; i++)
    {

        infile >> pointer[counter].gpa[i];

        if (i == 3)
            infile.ignore(4, '\n');
        else
            infile.ignore(4, ';');
    }
}

我遇到的问题是,我还必须提供第二种使用 C++ 字符串函数读取数据的方法。我不允许像第二种方法那样从上面读取数据。我必须遵循

的伪代码
  1. 从文件中读取一行
  2. 使用 C++ 字符串函数查找 ;
  3. 使用 C++ 字符串函数复制出该行到 ; 的部分 这将是名称字符串
  4. 使用 C++ 字符串函数查找下一个 ;
  5. 使用 C++ 字符串函数复制出该行的下一部分; 这将是 GPA 1
  6. 继续循环,直到读取完所有数据。

在伪代码的第 3 部分,我收到一条错误消息,指出无法从 const char* 转换为 char*。有办法解决这个问题吗?

string cppstr;
infile >> cppstr;
const char* mynewC = cppstr.c_str();
int position = cppstr.find(";", 0);
pointer[0].name.copy(mynewC, 0, position);   // this is part 3 that gives the erorr

这就是 substr() 的用途。

pointer[0].name=cppstr.substr(0, position);