I’m trying to get my program to loop through the file, taking in a load of information each time. However, at the moment after 2 correctly inputted lines it always goes to default, no matter what the contents of the file. Originally it was an eof while loop but I changed it to a for loop to try and fix it. Here’s my code:
ifstream furniture;
furniture.open("h://furniture.txt");
for(int i=0;i<=count;i++)
{
type=0;
furniture>>type>>name>>number>>material>>colour>>mattress;
switch (type)
{
case 1:
{
Item* item= new Bed(number, name, material, colour, mattress);
cout<<"working, new bed"<<endl;
v.push_back(item);
cout<<"working pushback"<<endl;
count++;
break;
}
case 2:
{
Item* item= new Sofa(number, name, material, colour);
cout<<"working, new sofa"<<endl;
v.push_back (item);
cout<<"working pushback"<<endl;
count++;
break;
}
case 3:
{
Item* item= new Table(number, name, material, colour);
cout<<"working, new table"<<endl;
v.push_back(item);
cout<<"working pushback"<<endl;
count++;
break;
}
default:
{
cout<<"Invalid input"<<endl;
type=0;
break;
}
}
}
I have tried a series of different solutions but nothing seems to have solved the problem.
Any help would be greatly appreciated.
ifstream‘soperator>>does not change the variable if the read fails, sotyperemains 0, thus the default branch is called. It seems like your file has a formatting error that makes the read fail.Based on your comment, that you might not have all values in the file all the time, here is what you could do:
The best way would be to use
getline()to read a full line, then usestringstreamto extract the values from the line, handling the optional values in the process:If you provide default values to all those variables, they will keep the default if the line is ill-formatted or does not contain all of them.
The advantage of using
getline()here is that the extraction viaop>>does not mess up subsequent lines if there is a problem with the current line.