使用字符串函数将数据从文件读入结构
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
我有一系列学生结构
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++。我不允许像在第二种方法中从上面那样读取数据。我必须遵循伪代码
- 从文件中读一行
- 使用 C++ 字符串函数查找 ;
- 使用 C++ 字符串函数将行的一部分复制到 ;这将是名称字符串
- 使用C++字符串函数查找下一个;
- 使用 C++ 字符串函数将行的下一部分复制到 ;这将是 GPA 1
- 继续循环,直到读取所有数据。
在伪代码的第 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);
相关文章:
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 将文件读入数据结构
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- (C++) 使用诅咒打印从文件中读入的新行
- 如何从文件到结构中读取特定数量的字符
- C++ 它没有从文件读回动态结构
- 从文件读入.多个分隔符?C++
- 从文件读入结构
- 使用字符串函数将数据从文件读入结构
- 函数从文件读入向量c++
- 从文件读到另一点c++
- 如何从文件读入双链表
- 从文件读入到数组
- 从文件读入矢量
- 将数字从文件读入数组
- 将数据从文件读入结构体,对数据进行排序并写入文件
- 从文件填充结构