Reputation: 83
void createVideoList(ifstream& ifile, Video videoArray[])
{
string title;
string star1;
string star2;
string producer;
string director;
string productionCo;
int inStock;
int count = 0;
Video newVideo;
getline(ifile, title);
while (ifile)
{
ifile >> inStock;
getline(ifile, title);
getline(ifile, star1);
getline(ifile, star2);
getline(ifile, producer);
getline(ifile, director);
getline(ifile, productionCo);
videoArray[count] = Video(inStock, title, star1, star2, producer, director, productionCo);
count++;
}
}
This is my code for a programming assignment. It will read in from a .txt file and is going to place the information into an array of a class I created.
The .txt is formatted like so:
3 (amount in stock)
Movie Title
Movie Star1
Movie Star2
Movie Producer
Movie Director
Movie ProductionCo
However, my code does not seem to be gathering the data correctly into the videoArray. I just switched over from Java so my C++ syntax is a little rusty. Am I using getline correctly? If I try to output one of the indexes, it has nothing in any of the variables. Thanks in advance!
Upvotes: 1
Views: 410
Reputation: 168876
Video newVideo;
getline(ifile, title);
while (ifile)
{
ifile >> inStock;
getline(ifile, title);
getline(ifile, star1);
...
It is mostly correct, but there are a few problems:
getline
, the one outside of the loop, shouldn't be there. What is it supposed to read?>>
with getline
. The >>
doesn't read in the remainder of the first line -- specifically, it leaves the \n
in the input stream. Use std::getline
or istream::ignore
to remove the pending end-of-line.std::vector
instead of an array, if the homework assignment allows it.Try:
while (ifile >> inStock && getline(ifile, temporary_string) &&
getline(ifile, title) &&
getline(ifile, star1) &&
...
getline(ifile, productionCo) )
{
videoVector.push_back(Video(inStock, title, ..., productionCo_));
// Or, as a less worthy alternative,
// videoArray[count] = Video(inStock, title, star1, star2, producer, director, productionCo);
// count++;
}
std::istream&
operator>>(std::istream& is, Video& v)
{
is >> v.inStock;
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(is, v.title);
std::getline(is, v.star1);
std::getline(is, v.star2);
std::getline(is, v.producer);
std::getline(is, v.director);
std::getline(is, v.productionCo);
return is;
}
std::vector<Video> void createVideoList(std::istream& ifile)
{
std::vector<Video> result;
std::istream_iterator<Video> begin(ifile), end;
std::copy(begin, end, std::back_inserter(result));
return result;
}
Upvotes: 4