![](/img/trans.png)
[英]I can't get my program to read the values from my input file correctly (2D array)
[英]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.