This is an assignment and I am stuck in the first information reading process.. I need to read information from a file "bank.txt". Every line of the file is like this: rice(China),13,2016-8-3,5kg
I have wrote a cpp for testing:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct Food
{
string name;
int quantity;
string expireDate;
string unit;
bool selected;
};
void all(Food item[]);
int main()
{
ifstream infile;
Food bank[100];
infile.open("bank.txt");
string text, temp[400];
string dummy;
int num;
stringstream linestream;
while(infile.good())
{
for(int i = 0; i < 100; i++)
{
for(int j = 0; j < 4; j++)
{
getline(infile, text, ',');
temp[4 * i + j] = text;
}
istringstream(temp[4 * i + 1]) >> num;
bank[i].name = temp[4 * i];
bank[i].quantity = num;
bank[i].expireDate = temp[4 * i + 2];
bank[i].unit = temp[4 * i + 3];
}
}
all(bank);
return 0;
}
void all(Food item[])
{
for(int i = 0; i < 100; i++)
cout << item[i].name << ".." << item[i].quantity << ".." << item[i].expireDate << ".." << item[i].unit << endl;
}
But this runs into some problems and the lines of odd numbers only displayed name.
How can I modify my code to make it behave normally??