I have a file that looks like:
Sister Act
Whoopi GoldBerg
Maggie Smith
Schwartz
Ardolino
Touch Stone Pictures
14
I am having trouble reading in the information and saving it to an object. I am not getting any error but I can not get program to read the information correctly.
My question is can anyone tell me what I need to change to make the my program read the file correctly.
Also each row can have multiple words and whitespace except for the integer in row 7.
string title, starName1,
starName2, producer,
director, prodCo;
int numCopies;
ifstream videoFile("videoDat.txt");
if (videoFile.is_open()) {
getline(videoFile, title);
getline(videoFile, starName1);
getline(videoFile, starName2);
getline(videoFile, producer);
getline(videoFile, director);
getline(videoFile, prodCo);
//getline(videoFile, numCopies); //compiler error
while (videoFile >> title >> starName1 >> starName2 >> producer >> director >> prodCo >> numCopies) {
//be able to do stuff with variables individually
}
}
I was thinking i needed to do something like:
while (getline(videoFile, title) && getline(videoFile, starName1) && getline(videoFile, starName2)
&& getline(videoFile, producer) && getline(videoFile, director) && getline(videoFile, prodCo) && videoFile >> numCopies) {
//be able to do stuff with variables individually
}
getline(videoFile, numCopies); //numCopies should not be an int, but a str.
numCopies is an int. Do this:
string numCopiesStr;
getline(videoFile, numCopiesStr);
int numCopies = std::stoi(numCopiesStr);
That should work.
Another way, but the error handling gets trickier, is to use std::cin:
std::cin >> numCopies;
That will read the int into the numCopies variable but will stop there exactly, after that, without getting the full line.
You cannot read strings separated by spaces with operator>>, it will stop at the first space. You need getline.
My recommendation is that you use a string numCopiesStr and convert to int inside the loop for each iteration.
Another solution (since C++14) is to use the std::quoted
modifier if you can change the format of the input file (add quotes to Sister Act, for example "Sister Act", etc). In that case you could use an int directly for numCopies and do this, as long as you quote every string that is not numbers:
while (std::quoted(videoFile) >> std::quoted(title) ... >> numCopies) {
}
See how to use std::quoted
here: http://en.cppreference.com/w/cpp/io/manip/quoted
Ah, and keep your cppreference.com always close to you, it can help a lot ;)