Ok, so I have to read from a text file. Some of the things we have to read are int values so I am using fstream to get them from the file.
The information we have to pull is in this format:
2011 Chevrolet Tahoe $30588
There is int year, string make, string model, and float price. There is a "$" dollar sign in front of price. So my fstream has to ignore the "$" sign.
Here is my fstream code so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <iostream>
#include <string>
#include <fstream>
#include "car.h"
using namespace std;
const int number=3;
const int maxPrice=25000;
int main()
{
int a;
string b; string c;
float d;
float e;
car cars [number];
int i, j;
float temp; //Price
int temp2; //Year
string temp3; //Make
string temp4; //Model
float temp5; //Miles
ifstream inFile; //declaring the File
for(i=0; i<number; i++)
{
inFile.open("carData.txt");
//cout << "Enter the YEAR of the car: ";
inFile >> a;
cars[i].setYear(a);
//cout << "Enter the MAKE of the car: ";
getline(inFile,b);
cars[i].setMake(b);
//cout << "Enter the MODEL of the car: ";
getline(inFile,c);
cars[i].setModel(c);
//cout << "Enter the number of MILES on the car: ";
inFile >> d;
cars[i].setMiles(d);
//cout << "Enter the PRICE of the car: ";
inFile >> e;
cars[i].setPrice(e);
//cout << " " << endl;
}
|
Then you're probably wondering what "car.h" is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
#include <string>
using namespace std;
class car
{
public:
//Set the Year, Make, Model, Miles, and Price.
void setYear(int a){year=a;}
void setMake(string b){make=b;}
void setModel(string c){model=c;}
void setMiles(float d){miles=d;}
void setPrice(float e){price=e;}
//Accessors
int getYear() const {return year;}
string getMake() const {return make;}
string getModel() const {return model;}
float getMiles() const {return miles;}
float getPrice() const {return price;}
private:
//Data Members
int year;
string make;
string model;
float miles;
float price;
};
|
Car.h is just a class with setters and getters to access the private data types.
The rest of my code, is just algorithms to sort out my arrays. So it isn't necessary for solving my problem.
So does anybody know how to fix it? When I run it, I just get this:
1 2
|
Cars listed under $25,000:
Press any key to continue...
|
Why isn't it sorting everything out? It works if I cin all the data manually, but why can't I pull anything from the file. I have the txt file in my project as a source file.
I have my code in the same syntax as our textbook teaches us. I don't know why it isn't working though.