C ++: Czytanie pliku CSV do tablicy struct
Pracuję nad zadaniem, w którym muszę odczytać plik CSV o nieznanej liczbie linii do tablicy strukturalnej. Tylko za pośrednictwem C ++, nie C (nie chcą, abyśmy łączyli oba).
Mam więc następujący kod:
// DEFINITION
struct items {
int ID;
string name;
string desc;
string price;
string pcs;
};
void step1() {
string namefile, line;
int counter = 0;
cout << "Name of the file:" << endl;
cin >> namefile;
ifstream file;
file.open(namefile);
if( !file.is_open()) {
cout << "File "<< namefile <<" not found." << endl;
exit(-1);
}
while ( getline( file, line) ) { // To get the number of lines in the file
counter++;
}
items* item = new items[counter]; // Add number to structured array
for (int i = 0; i < counter; i++) {
file >> item[i].ID >> item[i].name >> item[i].desc >> item[i].price >> item[i].pcs;
}
cout << item[1].name << endl;
file.close();
}
Ale kiedy uruchomię kod, aplikacja zwróci miejsce po przeczytaniu i myślę, że w ogóle nie czyta. Oto wyjście w konsoli:
Name of the file:
open.csv
Program ended with exit code: 0