【问题标题】:How to read string line by line [duplicate]如何逐行读取字符串[重复]
【发布时间】:2013-07-12 04:55:46
【问题描述】:

我想做一个应用程序学生管理器。我想用户输入学生的姓名和年龄信息,然后应用程序将其保存在文件中。我可以为我的应用程序保存它,但如何阅读它?这是我的代码,它可以读取文件中的所有学生信息,但第一个学生除外。不知道为什么?

#include<iostream>
#include<iomanip>
#include<fstream>

using namespace std;

struct St
{
    string name;
    int age;
};

class StManager
{
    int n;
    St *st;
public:
    StManager()
    {
        n = 0;
        st = NULL;
    }
    void input();
    void output();
    void readfile();
    void writefile();
};

void StManager::input()
{
    cout << "How many students you want to input?: ";
    cin >> n;
    st = new St[n];
    for(int i=0; i<n; i++) {
        cout << "Input student #"<<i<<":"<<endl;
        cout << "Input name: ";
        cin.ignore();
        getline(cin, st[i].name);
        cout << "Input age: "; cin>>st[i].age;
        cout <<endl;
    }
}

void StManager::writefile()
{
    ofstream f;
    f.open("data", ios::out|ios::binary);
    f<<n;
    f<<endl;
    for(int i=0; i<n; i++)
        f<<st[i].name<<setw(5)<<st[i].age<<endl;
    f.close();
}

void StManager::readfile()
{
    ifstream f;
    f.open("data", ios::in|ios::binary);
    f >> n;
    for(int i=0; i<n; i++) {
        getline(f, st[i].name);
        f>>st[i].age;
    }
    f.close();
}

void StManager::output()
{
    for(int i=0; i<n; i++) {
        cout << endl << "student #"<<i<<endl;
        cout << "Name: " << st[i].name;
        cout << "\nAge: " << st[i].age;
    }
}

int main()
{
   StManager st;
   st.input();
   st.writefile();
   cout << "\nLoad file..."<<endl;
   st.readfile();
   st.output();
}

【问题讨论】:

  • 请使用std::vector 而不是new[]。至少可以说你有内存泄漏。并查找“C++ getline skipping”,因为这也是一个问题。
  • @chris:为什么是矢量?对不起,我是 C++ 新手,我不明白
  • 老实说,在您用来学习的任何书籍或资源中,都应该在指针作为动态数组之前教授它。关于如何使用 std::vector 以及为什么它让生活变得如此美好的例子很多。
  • @chris:我不在学校学习,我只是在家学习
  • 一个好的book 将是一个非常有用的资产。

标签: c++


【解决方案1】:

您的input() 功能很好。问题是您正在调用readfile() 函数——这没有意义,因为您已经加载了一次输入数据。您的 readfile() 没有调用 ignore(),这会导致它覆盖您之前拥有的正确数据。

【讨论】:

  • 好的,非常感谢;)
猜你喜欢
  • 2011-07-19
  • 2010-11-08
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
相关资源
最近更新 更多