在C 中读取阵列结构
reading array struct in C++
我有一个项目,我必须将数据文件读取为一个称为本田的结构阵列,该阵列适用于10行数据。我很难成功阅读文本文件。在这里,我到目前为止的代码:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct Honda {
int id;
int year;
string model;
string trim;
string color;
int engine;
};
const int SIZE = 10;
void openInputFile(ifstream &, string);
int main()
{
Honda arr[SIZE];
ifstream inFile;
string inFileName = "C:\Users\Michael\Documents\inventory.txt";
openInputFile(inFile, inFileName);
for (int count = 0; count < SIZE; count++) {
inFile >> arr[count].id >> arr[count].year >> arr[count].trim >> arr[count].color >> arr[count].engine;
}
inFile.close();
return 0;
}
void openInputFile(ifstream &inFile, string inFileName)
{
//Open the file
inFile.open(inFileName);
//Input validation
if (!inFile)
{
cout << "Error to open file." << endl;
cout << endl;
return;
}
}
文本文件:库存.txt
1001 2014 Civic LX Red 4
1002 2014 Accord LX Blue 4
1005 2014 Accord EX Gold 6
1006 2014 Civic EX Black 4
1007 2014 Civic LX White 4
1010 2015 Accord EX White 6
1011 2015 Accord LX Black 4
1013 2015 Civic EX Red 4
1014 2015 Civic LX Beige 4
1015 2015 Accord EX Beige 6
您只是缺少代码逐行读取文件。
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <sstream>
using namespace std;
struct Honda {
int id;
int year;
string model;
string trim;
string color;
int engine;
};
const int SIZE = 10;
void openInputFile(ifstream &, string);
int main()
{
Honda arr[SIZE];
ifstream inFile;
string inFileName = "C:\temp\1.txt";
openInputFile(inFile, inFileName);
int count = 0;
string line;
while(inFile.good() && (getline(inFile, line)))
{
istringstream iss(line);
iss >> arr[count].id >> arr[count].year >> arr[count].model >> arr[count].trim >> arr[count].color >> arr[count].engine;
count++;
}
for (int i=0; i < 10; i++)
{
std::cout << arr[i].id << " " << arr[i].year << " " << arr[i].model << " " << arr[i].trim << " " << arr[i].color << " " << arr[i].engine << "n";
}
inFile.close();
return 0;
}
void openInputFile(ifstream &inFile, string inFileName)
{
//Open the file
inFile.open(inFileName);
//Input validation
if (!inFile)
{
cout << "Error to open file." << endl;
cout << endl;
return;
}
}
相关文章:
- 如何将来自文本文件的数据读取到结构的int阵列中
- 将数据从阵列火阵列传输到犰狳结构
- 将阵列的元素变为结构
- 带有柔性阵列构件的包装结构的便携式替代方案
- c/c qsort在结构内的结构阵列
- 生态2D结构阵列C
- 如何计算结构阵列内的平均值
- 传递结构C 的动态阵列
- 结构的动态阵列
- 工会结构阵列的初始化太多
- 读取阵列结构的值
- 将固定尺寸的阵列传递到结构
- C 阵列结构
- C 使用坐标结构的访问阵列元素
- 如何在C 中创建动态分配的2D结构阵列
- 在C 中读取阵列结构
- 最快可能的阵列结构,用于转换阵列
- 在结构阵列(AoS)和阵列结构(SoA)之间来回切换
- 阵列结构
- 用于将结构阵列(AoS)转换为阵列结构(SoA)的干净代码