Reputation: 11
The question may be worded poorly but I can do a better job explaining it here. Basically, I already initialized the struct and the 5 variables that need to utilize it. That all went off without a hitch, the problem came from the part of needing to use a text document to set the values of each struct. I need all 5 to be assigned in one go because the data is coming from a text file. To initialize one of the Variables the code looks like this;
int main(void){
ifstream inputFile;
ofstream outputFile;
char input[10];
char output[10];
cout << "Enter Input File: ";
cin >> input;
cout << "Enter Output File: ";
cin >> output;
inputFile.open(input);
outputFile.open(output);
struct Rental{
int year;
char make[10];
char model[10];
float price;
bool available;
};
Rental Car1, Car2, Car3, Car4, Car5;
inputFile >> Car1.make;
inputFile >> Car1.model;
inputFile >> Car1.price;
inputFile >> Car1.available;
I need to find a way to replace the Car1 (which is a struct variable) with all five of them so that the text document can just keep scanning down. Is there anyway to replace just the Car1 portion of the struct? Any help is appreciated!
EDIT: I forgot to add that I am restricted and unable to use the String library.
Upvotes: 0
Views: 52
Reputation: 43206
Overload the >>
operator for istream
std::istream& operator >>(std::istream &inputFile, Rental& car) {
inputFile >> car.make;
inputFile >> car.model;
inputFile >> car.price;
inputFile >> car.available;
return inputFile;
}
Now in main, you can do this:
int main () {
ifstream inputFile;
ofstream outputFile;
char input[10];
char output[10];
cout << "Enter Input File: ";
cin >> input;
cout << "Enter Output File: ";
cin >> output;
inputFile.open(input);
outputFile.open(output);
Rental Car1, Car2, Car3, Car4, Car5;
inputFile >> Car1 >> Car2 >> Car3 >> Car4 >> Car5;
inputFile.close()
...
}
This should work when using any std::istream
object, which means including std::cin
.
Upvotes: 1