Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ cin.getline() fail

my problem is that my program doesnt read the values that I enter by keyboard, only reads the 1st, the 2nd and last. I´ve tried with cin.ignore(); and other solutions but doesn work.

This is the input:

Insurance 1
Model: mazda

serial number: 60

Price: 9999

Contract number: 76Z

Contract money: 12

//after all characters, there was an \n enter.

This is the output:

Insurance 1
Model: mazda

serial number: 60

Price: 0

Contract number: 

Contract money: 12

I write here only a function, not all the 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);
}
like image 257
freinn Avatar asked Jun 18 '26 00:06

freinn


1 Answers

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

#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 );

This way, your inputs will always happen without glitches. No pending characters, no stream errors, no problems at all. The downside is that you'll have to convert numbers if you need them, but you're already doing that. ¡Buena suerte!

like image 57
Baltasarq Avatar answered Jun 19 '26 15:06

Baltasarq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!