从文本文件中读取数据并将数据插入到数组中
我发现的大部分信息都基于数字,但是我想使用单词。举例来说,如果我的文本文件看起来像这样:从文本文件中读取数据并将数据插入到数组中
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 ];
};
我不知道如果我需要使用分隔符或有事要告诉你的程序时停止在每个部分(性别,名字,姓氏等)。我可以在ifstream中使用getline函数吗?我在自己的代码中遇到了麻烦。我真的不知道从哪里开始,因为我现在不需要使用这样的一段时间。疯狂地搜索课本和谷歌找到类似的问题,但到目前为止,我没有太多的运气。我会用我发现的任何问题和代码更新我的文章。
我觉得@ 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;
}
既然你希望能够以显示他们,我'd增加一个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;
}
然后在af ILE充分的数据可以是这样的:
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));
同样,从矢量显示人的信息去是这样的:
std::copy(people.begin(), people.end(),
std::ostream_iterator<PeopleInfo>(std::cout, "\n"));
好让你开始:
// Include proper headers here
int main()
{
std::ifstream file("nameoftextfilehere.txt");
std::string line;
std::vector<std::string> v; // Instead of plain array use a vector
while (std::getline(file, line))
{
// Process each line here and add to vector
}
// Print out vector here
}
嗯,没事谢谢。我现在要玩这个。 – Hydlide 2012-02-28 01:29:29
一个结构可能比用于存储信息的数组更好。
struct person
{
std::string gender;
std::string first_name;
std::string last_name;
std::string position;
};
然后,你可以有一个人的矢量,并对其进行迭代。
对不起,忘了添加我正在使用一个结构体。我添加了信息。我也会研究矢量。 – Hydlide 2012-02-28 01:38:47
您还可以使用像bool maleFlag和bool femaleFlag这样的标志,并将它们设置为true和false,因为当您只读取一行上的'M'或'F'时,所以您知道与哪个性别关联后面的名字。
你也可以用你的的std :: ifstream的文件任何其他流:
//your headers
int main(int argc, char** argv)
{
std::ifstream file("name.txt");
std::string line;
std::vector<std::string> v; // You may use array as well
while (file.eof() == false) {
file >> line;
v.push_back(line);
}
//Rest of your code
return 0;
}
'while(file >> line)'会更好。 – devil 2012-02-28 01:58:38
我想你在'>>中省略了几个'p'。 – molbdnilo 2012-02-28 06:36:06
@molbdnilo:哟,谢谢。固定。 – 2012-02-28 07:04:20