【问题标题】:read line from text then copy into structure从文本中读取行然后复制到结构中
【发布时间】:2016-07-23 11:23:02
【问题描述】:

所以我了解了使用 while 循环逐行读取文本文件的基本概念,现在我的问题是如何读取每一行,然后将这些行的内容放入结构中的变量中?

我想出了如何将我的文本写入文件,但不知道如何存储同一个文件中的信息,所以这是我目前所拥有的,但它似乎不起作用:

这行得通:

void save(string fileName)
{
    Container *traverser = list;
    ofstream file;
    file.open(fileName);

    while (traverser != NULL){
        file << traverser->student->getFirstName() << endl;
        file << traverser->student->getLastName() << endl;
        file << traverser->student->getGrade() << endl;
        file << traverser->student->getEdu() << endl;
        traverser = traverser->next;
    }
}

这不是:

void load(string fileName)
{
    Container *traverser;
    Container* c;
    Student *s;
    string fname, lname;
    int grade;
    int edu;
    ifstream file;
    file.open(fileName);
    string line;

    while (getline(file, line)){
        file >> fname;
        file >> lname;
        file >> grade;
        file >> edu;
        s = new Student(fname, lname, grade, edu);
        c = new Container();
        c->student = s;
    }
}

是我的语法有问题还是我一起做错了?

该程序本质上会询问学生的姓名、年级和教育,然后将其存储到一个文本文件中,然后它应该将文本文件中的信息加载回程序中(我没有发布整个代码,因为有很多)。

谢谢!

附加信息:列表是结构(学生)的链表

【问题讨论】:

  • 这是作业吗?也就是说你不能使用vectorlist这样的标准容器吗?
  • 你读了一行然后你从文件流中解析更多的东西?确定不想用字符串流解析该行?
  • 你不需要getline。使用 while( 文件 >> fname >> lname >> 等级 >> edu )...

标签: c++ file input io output


【解决方案1】:

我怀疑你的数据在一行中

while (getline(file, line)){
    istringstream lstr(line);
    lstr >> fname;
    lstr >> lname;
    lstr >> grade;
    lstr >> edu;
    s = new Student(fname, lname, grade, edu);
    c = new Container();
    c->student = s;
}

这已经可以完成这项工作了。 编辑:你可能想#include &lt;sstream&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多