将文件中的逐行数据提取到C++中的动态数组中
Extracting line by line data from file into dynamic array in C++
我正在尝试从文件中提取数据并将其放入数据类型为DataBlock(DataBlock是结构)的动态数组中。问题是数据在 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
我搜索了很多,但找不到解决方案。明天是提交日期。如果您能帮助我,我将不胜感激。如果需要任何进一步的信息,请告诉我。
添加更多详细信息:这是数据块代码:
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');
}
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- C++中的动态铸造故障
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 控制允许动态运行c++的并发操作数
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 输出没有重复元素的动态数组(收缩数组)C++
- C++为线程工作动态地分割例程
- 正在插入动态数组
- 在c++中使用动态分配的问题
- C++中的动态对象与非动态对象
- 如何在动态数组上使用搜索函数
- 视觉studo 2019中的漫画和静态/动态绑定
- 从C++中的数字输入动态创建矩阵
- 如何从QToolBox中动态创建的QLineEdit中获取文本
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁