As you know, every time you do a reading in C ++, it blocks the execution until you press the enter key. Thus, for example, in the following code the result will not appear until the two numbers are entered and, subsequently, the enter key is pressed:
int a, b;
std::cin >> a >> b;
std::cout << a << b;
And, in addition, the program will work regardless of whether the separator used is a space (or twenty), or a line break. How is it possible?
std::cin
has certain characteristics that allow to simplify the reading mechanisms. So, when you write std::cin >> a
and assuming in this case that a
is of type int
, std::cin
will inspect the buffer input and discard all spaces, tabs and line breaks find until you find the first character convertible to numeric digit. In this way, when using std::cin
, you can not worry about line breaks and other separators.
However, getline
is not that smart and does not discard any characters. So, before this sequence:
int a;
std::string linea;
std::cin >> a;
std::getline(std::cin,linea);
We find that the reading of std::cin
has left a line break in the buffer input. Then std::getline
, whose role is to store in a variable of type std::string
everything it finds until the next line break, it finds an empty string.
The behavior of std::getline
has its raison d'être, and it is that this function is not the one to decide for you when this line break should be ignored and when not. That is your responsibility. On the other hand, std::cin
is not the one to decide when to delete the line break (or the separator or separators) that accompany the variable that is being read.
So, as you have been told in another answer, the solution is to discard the line break before calling std::getline
:
std::cin.ignore();
std::getline(std::cin, paises[i].pais);
These lines, if the user does not do weird things, will work fine, but if the user chooses to enter spaces after the confederacion text, the program will fail again and the reason is that with ignore
you are only discarding a character. To eliminate everything that is between the current position of the buffer and the first line break (included), you have to put the following:
std::cin.ignore(std::numeric_limits<int>::max(),'\n');
std::getline(std::cin, paises[i].pais);
Where numeric_limits
is a template that allows you to obtain useful information about native C ++ types. Thus, the max()
method will return the highest value that you can store in the type int
(which is the type with which we have specialized the template). This call of ignore
will discard a maximum of std::numeric_limits<int>::max()
characters, unless the character \n
is found before, in which case said character will also be discarded and the discard process will stop.