簡體   English   中英

我無法讓我的程序在函數中讀取我的文件

[英]I can't get my program to read my file in a function

我似乎無法弄清楚為什么我的代碼沒有讀取在交換機案例中使用的數據。 當我把它寫到一個文件時,它只是扯垃圾。 有人可以幫忙嗎?

void readData(Name element[], int size)
{
    ifstream infile("treeData.txt");

    int index = 0;
    string line, common, scientific, family;
    int name;

    infile.open("treeData.txt");
    {           
        {
            while((index < size) && (infile >> name >> common >> scientific >> family))
            {
                if(name >= 0 && name <= 100)
                {
                    infile >> element[index].treeID;
                    element[index].treeID = name;
                    infile >> element[index].commonName;
                    element[index].commonName = common;
                    infile >> element[index].scientificName;
                    element[index].scientificName = scientific;
                    infile >> element[index].familyName;
                    element[index].familyName = family;
                    index++;
                    size = index;
                }   
                else
                    cout << "The file was not found!";
            }
        }
    }       
    infile.close();
}

您的實現應該利用C ++ IOStreams庫的可擴展性功能。 您可以創建operator >>的重載,以便任何輸入流都可以將數據提取到Name對象中。 還建議不要將數據提取到數組中(就像在readData函數中嘗試過readData ),而是將其提取到單個對象中。 這樣,代碼可以構建在此功能之上。 它也是一種更合乎邏輯且更直接的執行提取方式:

std::istream& operator>>(std::istream& is, Name& n)
{
    if (!is.good())
        return is;

    int id;
    std::string line, common, scientific, family;

    if (is >> id >> common >> scientific >> family)
    {
        if (id >= 0 && id <= 100)
            n.treeID = id;

        n.treeID         = name;
        n.commonName     = common;
        n.scientificName = scientific;
        n.familyName     = family;
    }
    return is;
}

現在我們有了提取器,我們可以繼續創建一個Name對象數組,並為每個元素使用提取器:

std::ifstream infile("treeData.txt");
std::array<Name, 5> names;

for (auto name : names)
{
    infile >> name;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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