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

时间:2012-02-28 01:13:55

标签: c++ arrays visual-studio visual-studio-2010 visual-c++

我发现的大部分信息都是基于数字,但我想使用单词。例如,如果我的文本文件如下所示:

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函数吗?我在自己的代码中实现它时遇到了麻烦。我不确定从哪里开始,因为我暂时没有使用过这样的东西。疯狂搜索教科书和谷歌找到类似的问题,但到目前为止我没有太多运气。我会用我发现的任何问题和代码更新我的帖子。

5 个答案:

答案 0 :(得分:3)

我认为@ 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"));

答案 1 :(得分:1)

结构可能比存储信息的数组更好。

struct person
{
    std::string gender;
    std::string first_name;
    std::string last_name;
    std::string position;
};

然后你可以有一个人的矢量并迭代它。

答案 2 :(得分:0)

很高兴让你入门:

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

答案 3 :(得分:0)

您还可以使用bool maleFlag和bool femaleFlag等标志,并将它们设置为true和false,当您在一行中只读取“M”或“F”时,您就知道要与名称关联的性别接下来。

答案 4 :(得分:0)

您还可以将 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;
}
相关问题