I\'m trying to read data from a separated file into array of structures. Somehow
ID: 3625871 • Letter: I
Question
I'm trying to read data from a separated file into array of structures. Somehow this thing is driving me crazy. I did almost the same thing with my teacher on another example but her works, mine doesn't. Please please please help me. Thank you in advance Here is my complete code to read but it doesn't do it.include <iostream>
include <fstream>
include <iomanip>
include <string>
include <cctype>
using namespace std;
struct itemtype {
int id;
int onhand;
double price;
string description;
};
void get_data (itemtype[], int&); int main()
{
itemtype inventory [20];
int count = 0;
int i = 0;
get_data (inventory, count);
for (i = 0; i < count; i++);
{
cout << inventory[count].id << " " << inventory[count].onhand
<< " " << inventory[count].price << endl
<< inventory[count].description << endl << endl;
}
system ("pause");
return 0;
}
void get_data (itemtype inventory[], int& count)
{
ifstream input;
string file;
file = "data111.txt";
input.open(file.c_str());
count = 0;
input >> inventory[count].id;
while (!input.eof())
{
input >> inventory[count].onhand >> inventory[count].price;
getline(input,inventory[count].description);
count++;
input >> inventory[count].id;
}
input.close();
}
Explanation / Answer
please rate - thanks
see the cmments, and red
//missing #
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cctype>
using namespace std;
struct itemtype {
int id;
int onhand;
double price;
string description;
};
void get_data (itemtype[], int&); int main()
{
itemtype inventory [20];
int count = 0;
int i = 0;
get_data (inventory, count);
for (i = 0; i < count; i++) //had a ;
{
cout << inventory[i].id << " " << inventory[i].onhand //used count instead of i
<< " " << inventory[i].price << endl
<< inventory[i].description << endl << endl;
}
system ("pause");
return 0;
}
void get_data (itemtype inventory[], int& count)
{
ifstream input;
string file;
file = "data111.txt";
input.open(file.c_str());
count = 0;
input >> inventory[count].id;
while (!input.eof())
{
input >> inventory[count].onhand >> inventory[count].price;
input.ignore(); //flush enter from buffer
getline(input,inventory[count].description);
count++;
input >> inventory[count].id;
}
input.close();
}