The problem with mixing formatted input like std::cin >> n
with unformatted input like std::getline(std::cin, film)
is that formatted input stops when the format is filled and unformatted input doesn't skip any space characters: the issue you are observing is that reading of n
left a newline character which considered the end of the first string. The best way to solve this problem is to skip all leading whitespace using the std::ws
manipulator. In addition, you shall always verify that your input was successful. That is, you code would become something like this:
#include <iostream>
int main() {
int n;
if (std::cin >> n) {
std::string film;
std::cin >> std::ws; // not really an input, hence uncheckedd
for (int i(0); i != n && std::getline(std::cin, film); ++i) {
std::cout << '\'' << film << "'\n";
}
}
else {
std::cout << "ERROR: failed to read the number of films\n";
}
}
If you really need to have leading whitespaces in the name of the first film
you'd need to be more careful with ignoring whitespace and stop at the first newline. That is instead of std::cin >> std::ws
you'd use
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
This funny use of std::numeric_limits
(which is declared in the header <limits>
) makes sure that an arbitrary number of spaces could be skipped. You could also use some fixed number, say 10
, but hen skipping of spaces would stop after this number and you'd still potentially empty file. Also, if you actually entered the first film name on the same line as the number of files it would be skipped. As a result I think std::ws
is much better to use.