从文本文件中读取数据并将数据插入数组
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一起使用吗?我在自己的代码中实现这一点时遇到了问题。我真的不知道从哪里开始,因为我已经有一段时间不用这样的东西了。疯狂地在课本和谷歌上搜索类似的问题,但到目前为止,我运气不太好。我会用我发现的任何问题和代码更新我的帖子。
我认为@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-femaleFlags的标志,并在一行中只读取'M'或'F'时将它们设置为true和false,这样您就知道要将哪个性别与后面的名称关联起来。
您也可以将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;
}
相关文章:
- 逐行读取文件,并将数据插入变量和数组中
- Qt & SqlLite 将数据插入数据库
- C++ - 将数据插入到地图循环的地图中
- SQLite C/C++ 接口:将数据插入表时内存增加
- C++将 X 向量数据插入到另一个向量
- 如何通过 C 变量将数据插入表中
- 将数据插入一些复杂的数据结构-C
- 将数据插入C 中的文本文件中
- 如何通过c++中的应用程序将数据插入solr
- 在Windows上将数据插入文件
- C++链表——如何将每个新数据插入尾部
- C++链表实现多数据插入
- 在c++中,将数据插入到文件中的特定位置而不进行覆盖
- C++内存从将数据插入链表中泄漏
- 将数据插入多维向量并进行排序
- WINAPI SQLite C无法正确地将数据插入数据库
- 参照同一矢量的数据插入矢量
- PostgreSQL字节二进制数据插入
- Cuda有效地将数据插入到未排序的填充数组中
- 使用 ADO 将原始文件数据插入访问表的 BLOB("OLE 对象")字段