C ++ cin.getline () fail

my problem is that my program does not read the values ​​that I entered from the keyboard, only reads the 1st, 2nd and last. I tried cin.ignore (); and other solutions, but do not work.

This is the input:

Insurance 1
Model: mazda

serial number: 60

Price: 9999

Contract number: 76Z

Contract money: 12

// after all characters, was \ n enter.

This is the conclusion:

Insurance 1
Model: mazda

serial number: 60

Price: 0

Contract number: 

Contract money: 12

Here I write only a function, not the whole program:

struct tseg{
  char model[15]; //nombre del modelo
  char serialnumber[15]; //número de serie del coche
  double price; //precio de compra del coche
  char contractnumber[15]; //numero del seguro
  double contractmoney; //importe del contrato
};

bool registrarSeguro(tconces *a, int p, int total){ //p is the position!!!

      a[p].contrato = new tseg[a[p].numSegurosActuales];

      cout << "Enter model: " <<endl;
        cin.ignore();
      cin.getline(a[p].contrato[a[p].numSegurosActuales].model, 15);
      cout << "Enter serial number: " <<endl;
        cin.ignore();
      cin.getline(a[p].contrato[a[p].numSegurosActuales].serialnumber, 15);
      cout << "Enter price: " <<endl;
        cin.ignore();
      cin >> a[p].contrato[a[p].numSegurosActuales].price;
      cout << "Enter contract number: " <<endl;
        cin.ignore();
      cin.getline(a[p].contrato[a[p].numSegurosActuales].numContrato, 15);
      cout << "Enter contract number: " <<endl;
      cin >> a[p].contrato[a[p].numSegurosActuales].impContrato;

      a[p].numSegurosActuales++;
      sw = true;

 return (sw);
}
+3
source share
2 answers

You can use std :: getline () to read data into a string, and then copy the contents to your fields, limiting the number of characters to copy if necessary.

#include <util>
#include <cstring>

// ...

std::string input;
std::getline( cin, input );

// +1 char for end of string
std::strncpy( a[p].contrato[a[p].numSegurosActuales].model, input.c_str(), 14 );

, . , , . , , , . ¡ suerte!

+1

. , , , Contrato, , . ?

cin.ignore(), . , , . - , , , cin.ignore(1000, '\n'), 1000 , .

getline(), , , ignore().

+1

Source: https://habr.com/ru/post/1796574/


All Articles