如何逐行读取字符串

How to read string line by line

本文关键字:读取 字符串 逐行 何逐行      更新时间:2023-10-16

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

#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();
}

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