如何逐行读取字符串
How to read string line by line
我想成为一名应用程序学生经理。我想用户只输入学生的姓名和年龄信息,然后应用程序将其保存在一个文件中。我可以为我的应用程序保存它,但如何读取它?这是我的代码,它可以读取文件中的所有信息,但第一个学生除外。我不知道为什么?
#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()
,这会导致它覆盖您以前拥有的正确数据。
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 读取字符串文本输入以创建 2D 矢量
- 罗马数字到阿拉伯语 (vinculum) - 读取字符串中的字符
- C++:从文件中读取字符串和整数,并获得最大数字
- C++,从文件中读取字符串,分段错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 如何从内存中读取字符串?
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 我需要C++读取字符串数组中每个单词的第一个字母
- 读取字符串C++的字符时出错
- 读取字符串直到标志 (C++)
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++输入文件流无法从文件中读取字符串
- 读取字符串字符时出错
- 如何读取<字符串,矢量<对<int,字符串的映射>>>
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- C++ 使用 Strtok 读取字符串字符时出错
- 使用 getline 读取字符串,但每行中都有换行符