簡體   English   中英

從文本文件讀取並將數據插入數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM