scanf_s
does not remove the line break, which is what the second iteration of gets_s
reads. Simply delete that line break so that the reading is correct.
To eliminate that line break no it is advisable to use fflush
, since its use is not guaranteed by the standard, as indicated by the documentation of the function :
In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared ( but this is not portable expected behavior ).
Although there is no standard way to clean the input buffer, the most common option is to use the following loop:
int c;
while ((c = getchar()) != '\n' && c != EOF);
On the other hand, since you label the question as C ++, the logical thing is that you use functions of C ++ instead of those inherited from C.
In the case of using C ++, the stream input, stdin
yes that has a specific method to discard characters, the function ignore()
. This function will discard the given number of characters unless it is previously with the delimiter character passed as a parameter. If this second happens, the delimiter will be discarded and characters will be discarded.
#include <iostream>
#include <string>
struct Student
{
std::string name;
int grade;
};
Student students[10];
int main()
{
for (int i = 0; i < 10; i++)
{
std::cout << "Introduce el nombre del alumno:";
std::cin.ignore(std::numeric_limits<int>::max(),'\n');
std::getline(std::cin,students[i].name);
std::cout << "Introduce la nota del alumno:";
std::cin >> students[i].grade;
}
}
numeric_limits
is a template that has information about the basic types of the language. In this case the method max()
returns the largest number that can be stored in a variable of type int
. Using this value guarantees that before, whatever happens, we will find a line break (which is the character we want to eliminate).