Error in getline syntax (cin, vectoralumno [e] .name);

1

I throw compilation error in the following code.

#include <iostream>
#include <windows.h>
#include <string>
#include <sstream>
#include <stdio.h>
#include <conio.h>
#define TOTAL 1000

using namespace std;

struct Alumno
{
    string nombre[50];
    char apellido[50];
    int dni;
    int legajo;
};

int Ingresar_Alumno (int &e)
    {
        FILE *Estudiante;
        Alumno vectoralumno[TOTAL];

        if (Estudiante=fopen("Estudiante.dat", "ab+"))
        {
                std::string name;
                cout << "ingrese el nombre del alumno: ";
                getline(cin, vectoralumno[e].nombre);

                cout << "ingrese el apellido del alumno: ";
                getline(cin, vectoralumno[e].apellido);

                cout << "ingrese legajo del alumno: ";
                getline(cin, vectoralumno[e].legajo);

                cout << "ingrese el DNI del alumno: ";
                getline(cin, vectoralumno[e].dni);

            fwrite(&vectoralumno[e],sizeof(Alumno),1,Estudiante);

            }
        fclose(Estudiante);
        e++;
    }

Most likely, he's doing something wrong in the syntax. Previously I used cin >> vectoralumno[e].nombre; but when I entered the name and the person had two names (eg Andres Osvaldo) I skipped the option to enter surname

    
asked by Salva Castro 25.05.2017 в 23:25
source

1 answer

2
getline(cin, vectoralumno[e].legajo);

getline is a function designed to read text strings ... not numbers. To read integers, loose characters, decimal numbers, etc. you have to keep using cin::operator>> :

std::cin >> vectoralumno[e].legajo;

The problem that you can find in this case is that cin::operator>> does not eliminate the line break. If you make several readings you will see that the program starts doing strange things ... the solution is to clean the input buffer before the first getline :

std::cin.ignore(std::numeric_limits<int>::max());
std::getline(cin, vectoralumno[e].nombre);

numeric_limits is a template found in the limits library. It serves to obtain the range of values supported by a given type (In C ++ the types do not have a range of values set by the standard but depend on the platform on which the code is compiled).

Edit:

An error that I had not noticed:

struct Alumno
{
    string nombre[50]; // <<---
    char apellido[50];
    int dni;
    int legajo;
};

There you are declaring an array of 50 chains. If you use the class string instead of char[] you have to put it like this:

struct Alumno
{
    string nombre;
    char apellido[50];
    int dni;
    int legajo;
};
    
answered by 26.05.2017 / 08:42
source