使用字符串函数将数据从文件读入结构

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

本文关键字:从文件读 结构 数据 字符串 函数      更新时间:2023-10-16

我有一个文本文件,我想使用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

我有一系列学生结构

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 部分,我收到一个错误,说无法从常量字符*转换为字符*。有没有办法解决这个问题?

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);