Using the below code I am reading a .txt
file and I can't get it to output properly. It either doesn't break the first input correctly (with all comma delimiters) or it doesn't break properly if I only use a comma delimiter after only the item name (2nd item in the text file).
Here the code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inventoryFile;
string itemType[100], itemName[100], matCost[100], manHours[100];
// float matCost[100], manHours[100];
string temp;
inventoryFile.open("items2.txt");
cout << endl << endl;
if(!inventoryFile)
{
cout << "\n\nCan't read from file.\n";
exit(1);
}
int numItems=0;
getline(inventoryFile, temp, ',');
while(!inventoryFile.eof())
{
itemType[numItems] = temp;
inventoryFile >> itemName[numItems];
inventoryFile.ignore();
inventoryFile >> matCost[numItems];
inventoryFile.ignore();
inventoryFile >> manHours[numItems];
inventoryFile.ignore();
numItems++;
getline(inventoryFile, temp, ',');
}
for(int j=0; j<numItems; j++)
{
cout << "Item Type:\t" << itemType[j] << endl;
cout << "ITem Name:\t" << itemName[j] << endl;
cout << "Mats Cost:\t" << matCost[j] << endl;
cout << "Man Hours:\t$" << manHours[j] << endl << endl;
}
return 0;
}
The items.txt
file is:
1, Xiphos, 7.46, 2
2, Dao, 3.45, 2.7
3, Jian, 2.31, 0.5
1, Rapier, 8.32, 2.3
2, Hook Sword, 2.11, 0.75
1, Panzerstecher, 2.23, 1.25
2, Kopis, 14.89, 2.3
3, Longsword, 5.43, 0.5
1, Tuck, 2.5, 15
1, Small Sword, 7.5, 2
3, Broadsword, 0.5, 0.25
The items2.txt
file is:
1 Xiphos, 7.46 2
2 Dao, 3.45 2.7
3 Jian, 2.31 0.5
1 Rapier, 8.32 2.3
2 Hook Sword, 2.11 0.75
1 Panzerstecher, 2.23 1.25
2 Kopis, 14.89 2.3
3 Longsword, 5.43 0.5
1 Tuck, 2.5 15
1 Small Sword, 7.5 2
3 Broadsword, 0.5 0.25