Tag Archives: #212121

#Mastery27 – Validated user input in C++

Validar inputs de usuario en c++

En C++ tenemos la opcion de validar datos alfanumericos o los llamados strings. Estos inputs se comportan como cualquier número, por lo que su uso no es muy dificil. Primero debemos conocer las reglas básicas:

Reglas basicas:

  • No deje pasar los datos no válidos en adelante
  • Validar los datos en el momento de entrada.
  • Siempre dar la retroalimentación significativa usuario
  • Dígale al usuario lo que usted espera de leer como entrada

Ejemplos:

/* example one, a simple continue statement */
  

main()
{
	int     valid_input;    /* when 1, data is valid and loop is exited */
	char    user_input;     /* handles user input, single character menu choice */

	valid_input = 0;
	while( valid_input == 0 ) {
		printf("Continue (Y/N)?n");
		scanf("  %c", &user_input );
		user_input = toupper( user_input );
		if((user_input == 'Y') || (user_input == 'N') )  valid_input = 1;
		else  printf("07Error: Invalid choicen");
	}
}
Salida del programa:
Continuar (Y / N) ?
b
Error: eleccion no válida
Continuar (Y / N) ?
N


 

Aqui otro ejemplo:

/* example two, getting and validating choices */
  

main()
{
	int     exit_flag = 0, valid_choice;
	char    menu_choice;
	
	while( exit_flag == 0 ) {
		valid_choice = 0;
		while( valid_choice == 0 ) {
			printf("nC = Copy FilenE = ExitnM = Move Filen");
			printf("Enter choice:n");
			scanf("   %c", &menu_choice );
			if((menu_choice=='C') || (menu_choice=='E') || (menu_choice=='M'))
				valid_choice = 1;
			else
				printf("07Error. Invalid menu choice selected.n");
		}
		switch( menu_choice ) {
			case 'C' : ....................();    break;
			case 'E' : exit_flag = 1;  break;
			case 'M' : ....................();  break;
			default : printf("Error--- Should not occur.n"); break;
		}
	}
}

Salida del programa 
C = Copiar archivo
E = Salir
M = Mover archivo
Introduzca elección :
x
Error . Opción de menú seleccionada no válida 
C = Copiar archivo
E = Salir
M = Mover archivo
Introduzca elección :
E

 

Referencias: http://ftp.tuwien.ac.at/languages/c/programming-bbrown/c_032.htm

27 1017

MASTERY09

Basic types and their use in C++  

Include the iostream and using namespace std . it must define the main function(main).

Diferent types of variables, int, double,float, and a value for these.

Int: only stores integers.

Double: stored real numbers with decimals.

Float: Also stores real numbers with decimals.

Then compile and run the program.