我有一个项目,我必须将数据文件读入一个名为Honda的结构数组中,该数组的大小适用于10行数据。我无法成功读取文本文件。这是我到目前为止的代码:
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
文本文件:inventory.txt
import csv
fieldWanted = 'RELH2'
with open('south_camden_topo_v2.xlsx - south_camden_topo_v2.csv') as csvFile:
reader = csv.reader(csvFile)
headings = next(reader)
fieldIndex = headings.index(fieldWanted)
print (headings)
count = 0
for row in reader:
print (row)
print (fieldWanted, ':', row[fieldIndex])
count += 1
if count > 5 :
break
答案 0 :(得分:1)
你只是缺少逐行读取文件的代码。
#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;
}
}