In my class I have this ifstream method I need it to read a file and write the information in my already created objects Something is wrong with the code First the a.engiene value is inserted with a space before the value - " gasoline"
And when the second object and third object are given values, the method does not assign the correct value for each attribute.
friend ifstream& operator>>(ifstream& in, Auto &a)
{
char temp[31];
temp[0] = '\0';
in.getline(temp, 30, ':');
if (temp[0])
{
in.getline(temp, 30, ':');
delete[]a.engine;
a.engine = new char[strlen(temp) + 1];
strcpy(a.engine, temp);
in.getline(temp, 30, ':');
a.max_speed = atoi(temp);
in.getline(temp, 30, ':');
a.engine_cc = atoi(temp);
in.getline(temp, 30, ':');
a.avg_consumption_urban = atoi(temp);
in.getline(temp, 30, ':');
a.avg_speed_urban = atoi(temp);
in.getline(temp, 30, ':');
a.avg_consumption = atoi(temp);
in.getline(temp, 30, ':');
a.avg_speed = atoi(temp);
return in;
}
else return in;
This is how I call the method in main:
ifstream f1("autoc.txt", ios_base::in);
f1 >> auto1 >> auto2 >> auto3;
This is the file data:
auto1
engine: gasoline
max_speed: 250
engine_cc: 1980
avg_consumption_urban: 11
avg_speed_urban: 50
avg_consumption: 8
avg_speed: 100
auto2
engine: diesel
max_speed: 230
engine_cc: 1600
avg_consumption_urban: 9
avg_speed_urban: 50
avg_consumption: 6
avg_speed: 80
auto3
engine: hybrid
max_speed: 190
engine_cc: 1450
avg_consumption_urban: 7
avg_speed_urban: 50
avg_consumption: 4
avg_speed: 90
This is the output window: https://i.sstatic.net/OwuZz.jpg
This is not a duplicate to my other question. I have this code that almost works. I need to make it assign the correct value to my attributes for each object.
in.getline(temp, 30, ':');
reads up to the :
, which are the property names. You also want to extract the values after that, so you need to add
in.getline(temp, 30);
after each
in.getline(temp, 30, ':');
But bear in mind that your program completely ignores the property names and just goes by the order of values. I hope this solves your problems once and for all.
I'm afraid to add a neater version of doing this (you might again ask about), so I'll just mention it (like I did in the answer on your original question). It's about using std::string temp;
and std::getline
instead of std::istream::getline
.