I am working on an assignment that requires me to read in a text file with text that looks like this
974 Headlight_LoBeam 6 12.87 5 3
I am able to open the file successfully and just for testing purposes I am able to use getline() to get the first line of the file. My issue is that when I am trying to get each line and add the data into my struct I am not getting the proper data. I am sure it is something simple that I am missing but I have yet to figure it out. To clarify I cannot use getline() to get the full line and then parse out the info I want into my struct. I have to use the "myfile >>" way of doing this according to my assignment. I do not get any compile errors. Here is the code currently. Currently the while loop is set only to run once to avoid a long list of incorrect data. Once I can get the data into the struct I will change the while loop to run for all the lines in the text file.
/*
* File: main.cpp
* Author: Rob
*
* Created on September 1, 2011, 5:19 PM
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
/*
*
*/
int main() {
int const MAXINV = 5;
string line;
struct inventoryinfo
{
double partnumber; //part number
string descript;
int numinstock;
float valueeach;
int reorderlev;
int reordernum;
};
inventoryinfo inventory[MAXINV];//declares the array of structs with the max # allowed
//variable declarations
int counter;
//declare and open the file containing
//inventory information
ifstream MyFile;
MyFile.open("inv.txt");
if (MyFile.is_open())
{ getline (MyFile,line);
cout << line << endl;
cout << "File successfully opened" <<endl;
}
else
{
cout << "Error opening file" << endl;
}
counter = 0;
while(counter <= 0){
MyFile >> inventory[counter].partnumber;
MyFile >> inventory[counter].descript;
MyFile >> inventory[counter].numinstock;
MyFile >> inventory[counter].valueeach;
MyFile >> inventory[counter].reorderlev;
MyFile >> inventory[counter].reordernum;
cout <<"Counter = "<<counter<<endl;
counter++;
MyFile.close();
}
int counter1 = 0;
while(counter1 <= 0){
cout <<"Part # "<<inventory[counter1].partnumber<< endl;
cout <<"Descript "<< inventory[counter1].descript<< endl;
cout <<"Number in stock "<< inventory[counter1].numinstock<< endl;
cout <<"Value Each "<< inventory[counter1].valueeach<< endl;
cout <<"Reorder Level "<< inventory[counter1].reorderlev<< endl;
cout <<"Reorder Number "<< inventory[counter1].reordernum<< endl;
cout <<"Counter1 is "<<counter1<<endl;
counter1++;
}
return 0;
}
Here is the current output:
974 Headlight_LoBeam 6 12.87 5 3
File successfully opened
Counter = 0
Part # 5
Descript 027
Number in stock 2
Value Each 2.8026e-45
Reorder Level 2673832
Reorder Number 1975982290
Counter1 is 0
Press [Enter] to close the terminal ...
Thanks for any help in advance.
-Rob