Validate Data in c ++

2

I need to validate the numerical data entry in c ++, I am using:

#include<iostream>
#include<stdio.h>

using namespace std;

int main() {
    int dato;
    cout<<"Ingrese un valor para dato: ";

    while( ( cin>>dato ).fail() ) { //comprobamos los flags de error con la referencia que devuelve el operador >>
        cin.clear(); //reseteamos los flags
        fflush(stdin); //limpio buffer de entrada
        cout<<".:Entrada Invalida:."<<endl;
        cout<<"Ingrese un valor para dato: ";  
    }

    cout<<"\n\tEl Dato es: "<<dato;

    return 0;
}

This works correctly for one-character entries and strings, also for Alpha-Numeric strings but only when numbers are entered after a character.

Example:

Ingrese un valor para dato: t
.:Entrada Invalidada:.
Ingrese un valor para dato: ttt
.:Entrada Invalidada:.
Ingrese un valor para dato: rgwsw934954
.:Entrada Invalidada:.

If I put an entry as 3x where I first enter a number and then the characters, it takes answer 3, but I need to ask for a new data.

Ingrese un valor para dato: 1234qwerty

    El Dato es: 1234 
    
asked by José F 14.10.2017 в 13:53
source

1 answer

3

The formatted entry has that slight discomfort : If the beginning of the string read matches with what is expected, the necessary data is taken and the rest is left in the < em> buffer .

If you want to make sure that the complete entry has only numbers, you'll have to check it yourself:

#include <string>
#include <cstdlib>
#include <iostream>

using namespace std;

int main( ) {
  string str; // Cadena leída
  int dato;

  cout << "Ingrese un valor para dato: ";

  while( getline( cin, str ) ) {
    const char *idx = str.c_str( );

    // Mientras que no lleguemos al final de la cadena,
    // y el caracter sea un dígito.
    while( *idx && *idx >= '0' && *idx <= '9' )
      ++idx;

    // Si llegamos al final de la cadena, la validación es correcta.
    if( !( *idx ) )
      break;

    cout << "Entrada inválida.\n";
  }

  // Convertimos la cadena en entero.
  dato = atoi( str.c_str( ) );
  // Y lo mostramos.
  cout << "El dato es: " << dato << endl;

  return 0;
}

The previous code checks that the entry is only digits . Does not take into account the size of the entry, nor does it consider a possible - sign to indicate a negative number.

    
answered by 14.10.2017 / 20:03
source