[英]Extracting line by line data from file into dynamic array in C++
我試圖從文件中提取數據,並將其放入類型為DataBlock的動態數組中(DataBlock是struct)。 問題在於,在for循環的第一個迭代中正確地提取了數據,但隨后沒有。 我已經調試過,問題是在for循環的第一次迭代並將第一次迭代的最后一個值分配給整個數組之后,指針沒有移到下一行。
編輯:現在我意識到問題是由於文件中的“ ****”,因為它們不是整數。 但是它們是必需的(它們有助於計算記錄大小)是否可以跳過帶有“ ****”的行。 ?
這是文件中的數據:
3
4
2029
23
45
459
***
1
2
2015
3
4
20
***
當數據移動到數組並顯示時,它顯示:
3
4
2029
23
45
459
***
459
459
459
459
459
459
***
這是代碼:
DataBlock *writetoarray(string uname)
{
int size;
int data;
size = SizeOfArray(uname);
cout << "size:" << size << endl;
DataBlock *ptr = new DataBlock[size];
ifstream displayf;
displayf.open(uname.c_str());
int i = 0;
for (int i = 0; i < size; i++)
{
displayf >> data;
//istream& getline(displayf >> data);
ptr[i].date = data;
cout << ptr[i].date << endl;
displayf >> data;
ptr[i].month = data;
cout << ptr[i].month << endl;
displayf >> data;
ptr[i].year = data;
cout << ptr[i].year << endl;
displayf >> data;
ptr[i].hrs = data;
cout << ptr[i].hrs << endl;
displayf >> data;
ptr[i].min = data;
cout << ptr[i].min << endl;
displayf >> data;
ptr[i].bgl = data;
cout << ptr[i].bgl << endl;
displayf >> data;
cout << "***" << endl;
}
displayf.close();
return ptr;
}//function ends
我已經搜索了很多,但是找不到解決方案。 明天是提交日期。 如果您能幫助我,我將非常感謝。 請告訴我是否需要任何進一步的信息。
添加更多詳細信息:這是DataBlock代碼:
struct DataBlock
{
int date, month, year, hrs, min, bgl;
};
對於文件迭代,最好使用getline函數。 請嘗試以下操作,看它是否對您有幫助:
std::string fileLine;
while(!displayf.eof()) //Will navegate in the file until it reachs the end.
{
getline(displayf, fileLine);
//Now your file data is in fileLine variable
/*Do what your need with the data here*/
}
對於while循環的每個交互,fileLine將有一行文件,當文件到達末尾時,循環將自動結束。
該問題已通過以下方式解決:
出現問題的是星號,因為它們不是int,但提取行的變量是int類型
在提取星星后就解決了這個問題:
displayf >> data;
if (displayf.failbit)
{
cout << "***" << endl;
displayf.clear();
displayf.ignore(numeric_limits<streamsize>::max(), '\n');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.