我找到的大部分信息都是基于数字,但我想使用文字。例如,如果我的文本文件如下所示:
M
Gordon
Freeman
Engineer
F
Sally
Reynolds
Scientist
我希望能够将每一行放入一个数组中并像这样输出:
Gender: M
First Name: Gordon
Last Name: Freeman
Job: Engineer
Gender: F
First Name: Sally
Last Name: Reynolds
Job: Scientist
这个列表可以继续下去,但现在有两个就好了。
我目前正在使用一个结构来保存信息:
struct PeopleInfo
{
char gender;
char name_first [ CHAR_ARRAY_SIZE ];
char name_last [ CHAR_ARRAY_SIZE ];
char job [ CHAR_ARRAY_SIZE ];
};
我不确定是否需要使用分隔符或其他东西来告诉程序何时在每个部分(性别、名字、姓氏等)处停止。我可以将 getline 函数与 ifstream 一起使用吗?我在自己的代码中无法实现它。我不太确定从哪里开始,因为我已经有一段时间没有使用过这样的东西了。疯狂地翻遍教科书和谷歌寻找类似的问题,但到目前为止我没有太大的运气。我会用我发现的任何问题和代码更新我的帖子。
最佳答案
我认为 @user1200129 走在正确的轨道上,但还没有完全把所有的部分放在一起。
我会稍微改变一下结构:
struct PeopleInfo
{
char gender;
std::string name_first;
std::string name_last;
std::string job;
};
然后我会重载 operator>>
对于该结构:
std::istream &operator>>(std::istream &is, PeopleInfo &p) {
is >> p.gender;
std::getline(is, p.name_first);
std::getline(is, p.name_last);
std::getline(is, p.job);
return is;
}
既然你希望能够显示它们,我会添加一个 operator<<
也这样做:
std::ostream &operator<<(std::ostream &os, PeopleInfo const &p) {
return os << "Gender: " << p.gender << "\n"
<< "First Name: " << p.name_first << "\n"
<< "Last Name: " << p.name_last << "\n"
<< "Job: " << p.job;
}
然后读取一个充满数据的文件可以是这样的:
std::ifstream input("my file name");
std::vector<PeopleInfo> people;
std::vector<PeopleInfo> p((std::istream_iterator<PeopleInfo>(input)),
std::istream_iterator<PeopleInfo(),
std::back_inserter(people));
同样,从 vector 中显示人物信息的方式如下:
std::copy(people.begin(), people.end(),
std::ostream_iterator<PeopleInfo>(std::cout, "\n"));
关于c++ - 从文本文件读取数据并将数据插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474974/