我有一個項目中,我必須讀出的數據文件轉換成稱爲本田一個結構陣列,其尺寸適合10行數據。我無法成功讀取文本文件。這裏的代碼我到目前爲止:讀取陣列結構在C++
#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;
}
}
文本文件:inventory.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
儘量避免使用C風格的數組,而是使用'std :: vector'或類似的東西。你的魔法極限10是非常隨意的。 – tadman
在互聯網上搜索「stackoverflow C++讀取文件空間分隔」。這裏已經有太多類似的帖子了。 –
顯示的代碼忘記讀取'arr [count] .model'。 –