[英]Reading from a text file and inserting data into an array
我发现的大多数信息都是基于数字的,但是我想使用单词。 例如,如果我的文本文件如下所示:
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一起使用吗? 我在自己的代码中无法实现。 我不太确定从哪里开始,因为我已经有一段时间没有使用这种东西了。 疯狂地搜索教科书和Google,以发现类似的问题,但是到目前为止,我还没有遇到太多的运气。 我将使用发现的任何问题和代码来更新我的帖子。
我认为@ 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));
同样,从矢量显示人的信息类似:
std::copy(people.begin(), people.end(),
std::ostream_iterator<PeopleInfo>(std::cout, "\n"));
结构可能比存储信息的数组更好。
struct person
{
std::string gender;
std::string first_name;
std::string last_name;
std::string position;
};
然后,您可以拥有一个人员向量并对其进行迭代。
好吧,让您开始:
// 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
}
您还可以使用诸如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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.