从文本文件中读取数据并将数据插入数组

Reading from a text file and inserting data into an array

本文关键字:数据 插入 数组 读取 文本 文件      更新时间:2023-10-16

我发现的大多数信息都是基于数字的,但我想使用单词。例如,如果我的文本文件看起来像这样:

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;
}