This is my funcoes.h where i keep my fuctions, my problem is at this line cout << "Digite o tipo de EPI a ser cadastrado: \n"; My program just skips the next getline(); and i cannot read user input. looks like this
The next getline() is working fine, so i've no ideia where the problem is.
#ifndef FUNCOES_H_INCLUDED
#define FUNCOES_H_INCLUDED
#include "Estruturas.h"
#include <string.h>
using namespace std;
void cadastroInsumos(tVacina vacinas[], tMedicamento medicamento[], tEPI EPIs[])
{
int casee, i;
cout << "Qual insumo voce deseja cadastrar?\n" << endl;
cout << "[1] - Vacina" << endl;
cout << "[2] - Medicamento" << endl;
cout << "[3] - EPI" << endl;
cout << "-----------------------------------------" << endl;
cin >> casee;
system("CLS");
if (casee == 3)
{
tEPI epi;
cout << "Digite o tipo de EPI a ser cadastrado: \n";
getline(cin, epi.tipo);
cout << "Digite o nome do EPI a ser cadastrado: \n";
getline(cin, epi.dadosEPI.nome);
cout << "Digite o valor unitario: \n";
cin >> epi.dadosEPI.valorUnitario;
cout << "Digite a quantidade de itens: \n";
cin >> epi.dadosEPI.qItens;
cout << "Digite a data de vencimento: \n";
cin >> epi.dadosEPI.dataVencimento.dia;
cin >> epi.dadosEPI.dataVencimento.mes;
cin >> epi.dadosEPI.dataVencimento.ano;
cout << "Digite o nome do fabricante: \n";
cin >> epi.dadosEPI.nomeFabricante;
cout << "Digite informacoes detalhadas sobre o EPIs: \n";
cin >> epi.detalhesEPI;
EPIs[1] = epi;
system("CLS");
}
}
/*void criarVacinas(tVacina vacinas[])
{
}
void criarMedicamentos(tMedicamento medicamento[])
{
}
void criarEPIs(tEPI EPIs[])
{
}*/
#endif // FUNCOES_H_INCLUDED
My main looks like this
#include <iostream>
#include <string>
#include "Estruturas.h"
#include "Funcoes.h"
using namespace std;
int main()
{
int casee;
tVacina vacinas[10];
tMedicamento medicamentos[10];
tEPI EPIs[10];
cout << "------UFPB 2021 - ENGENHARIA DE COMPUTACAO - PROJETO POO------" << endl;
cout << "Grupo: Leonardo Chianca, Savio Nazario e Yuri Fernandes\n" << endl;
cout << "------Bem-vindo ao Sistema de Gerenciamento de insumos------\n" << endl;
while(true)
{
cout << "Digite o numero correspondente a operacao que deseja executar: \n" << endl;
cout << "[0] - Fechar Sistema" << endl;
cout << "[1] - Cadastro de Insumos no estoque do MS" << endl; //vacinas, medicamentos e EPIs
cout << "[2] - Consulta de Insumos disponiveis no estoque do MS" << endl;
cout << "[3] - Consulta da descricao de Insumos disponiveis no estoque do MS" << endl; //Informacoes sobre seus atributos
cout << "[4] - Consulta de Insumos disponiveis no estoque do MS por tipo" << endl; //vacina, medicamentos e EPIs
cout << "[5] - Consulta de Insumos distribuidos para os estados" << endl;
cout << "[6] - Consulta da descricao de Insumos disponiveis nos Estados" << endl; //Informacoes sobre seus atributos
cout << "[7] - Consulta de Insumos disponiveis no estoque dos Estados por tipo" << endl; //Vacinas, medicamentos e EPIs
cout << "[8] - Consulta de Insumos disponiveis no estoque por Estado" << endl; //Estado passado como paramentro
cout << "[9] - Distribuir Insumos entre Estados\n" << endl; //O parametro deve ser o estado + o tipo de insumo que saira do estoque do MS
cout << "---------------------------------------------------------------------------" << endl;
cin >> casee;
system("CLS");
switch(casee)
{
default: return 0;
break;
case 1: cadastroInsumos(vacinas, medicamentos, EPIs);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
case 9:
break;
}
}
}
It is caused because of this line:
cin >> casee;
This line reads a number into the variable "casee".
However, the newline '\n' entered after the number is not read.
Then, the pending newline is read by the following getline:
getline(cin, epi.tipo);
Then, epi.tipo is assigned a "\n" value.
Related
I got this code and the problem is that I can only continue the loop forever but i can't exit it. I have been struggling with this for quite some hours and figure out where i do wrong. I think that its mostly about the do while in the end but since I am new to this there might be somewhere else in the code.
#include <iostream>
using namespace std;
int main() {
locale swedish("swedish");
locale::global(swedish);
int saldo = 1000;
int bet;
int vinst;
char val;
int nummer = 0;
char spelaigen;
char spelainteigen;
/*Här "presenteras" programmet med lite cout's som mest välkomnar dig till roulett och ger dig ett saldo*/
cout << "Username: Användare" << endl;
cout << "Password: ********" << endl;
cout << "Logging in: " << endl;
cout << "Searching for a live room: " << endl;
cout << "Initializing mainframe: \n" << endl;
cout << "Välkommen till Save7heCasino" << endl;
cout << "Här spelar du Roulette " << endl;
cout << "Du har " << saldo << " att spela för." << endl;
while (true)
{
cout << "Du får välja mellan 100, 300 eller 500 att spela för." << endl;
cin >> bet;
if (saldo < bet)
{
cout << "Ditt saldo är för lågt." << endl;
break;
}
if (bet == 100)
{
cout << "Du valde insatsen 100:-" << endl;
cout << "Ditt saldo är " << saldo - bet << endl;
}
else if (bet == 300)
{
cout << "Du valde insatsen 300:-" << endl;
cout << "Ditt saldo är " << saldo - bet << endl;
}
else if (bet == 500)
{
cout << "Du valde insatsen 500:-" << endl;
cout << "Ditt saldo är " << saldo - bet << endl;
}
else
{
cout << "Getfucl :)" << endl;
break;
}
srand(time(0));
int vinst = rand() % 36 + 1;
cout << "\n";
cout << "-Vinsttabell: " << endl;
cout << "-Vinst: Färg ger 2x din insats." << endl;
cout << "-Vinst: Nummer ger 10x din insats." << endl;
cout << "\n";
cout << "Vill spela på färg [1] eller nummer [2]: " << endl;
cin >> val;
/*Här väljer jag 1 eller 2 och deklarerar "val" till det nummret
Om jag väljer 1 så kommer if-satsen under att köras och väljer jag 2 så kommer else if-satsen att köras
Om jag väljer 1 så kommer den att deklarera om "val" för den nya input som blir, i detta fall "r" eller "b"
och fortsätta att köras i en ny if-sats som hanterar inmatning 1 */
/*Här kör jag en if-sats för svaret 1 som är färg, identifieraren "val" deklareras då ett nytt värde som
matas in utav användaren som nu i sin tur får välja "r" eller "b". Det finns 2 if-satser för val 1, en för respektive färg, "r" och "b" som avgörs omÄ
random funktionen är delbar eller inte vilket talar om utifall svaret blev rött eller svart.*/
if (val == '1')
{
cout << "Vilken färg vill du spela? [r] för Röd och [b] för Svart " << endl;
cin >> val;
if (val == 'b')
{
if (vinst % 2 == 0)
{
cout << "Resultatet blev Svart: " << vinst << endl;
saldo = saldo + bet * 2 - bet;
cout << "Du vann: " << bet + bet << endl;
cout << "Ditt nya saldo är: " << saldo << endl;
}
else
{
cout << "Du förlorade resultatet blev Rött: " << vinst << endl;
saldo = saldo - bet;
cout << "Ditt nya saldo är: " << saldo << endl;
}
}
if (val == 'r')
{
if (vinst % 2 != 0)
{
cout << "Resultatet blev Rött: " << vinst << endl;
saldo = saldo + bet * 2 - bet;
cout << "Du vann: " << bet + bet << endl;
cout << "Ditt nya saldo är: " << saldo << endl;
}
else
{
cout << "Du förlorade resultatet blev Svart: " << vinst << endl;
cout << "Du förlorade: " << endl;
saldo = saldo - bet;
cout << "Ditt nya saldo är: " << saldo << endl;
}
}
}
/*Här hamnar du om du valde "2" i det första steget efter du valt insats. Även i denna if-sats finns det 2 andra if-satser ,*/
if (val == '2')
{
cout << "Vilket nummer?: ";
cin >> val;
if (vinst == val)
{
cout << "Grattis du vann: " << vinst << endl;
cout << "Du vann: " << bet * 10 << endl;
saldo = saldo + bet * 10 - bet;
cout << "Ditt nya saldo är " << saldo << endl;
}
else if (vinst!=val)
{
saldo = saldo - bet;
cout << "Fel nummer, det rätta nummret var: " << vinst << " - Ditt nya saldo är: " << saldo << endl;
}
}
do
{
cout << "Vill du spela igen?: j/n?: " << endl;
cin >> spelaigen;
} while (spelaigen == 'j' || spelaigen == 'J');
}
return 0;
}
This code seems wrong to me (but apologies I don't read Swedish)
do
{
cout << "Vill du spela igen?: j/n?: " << endl;
cin >> spelaigen;
} while (spelaigen == 'j' || spelaigen == 'J');
I think what you are doing is asking whether the user want to try again, yes or no? If that's right then all you need is an if statement which breaks out of the main loop if the answer is no.
cout << "Vill du spela igen?: j/n?: " << endl;
cin >> spelaigen;
if (spelaigen == 'n' || spelaigen == 'N')
break;
Now that code works but you could also check if the answer is yes or no and ask again if it is neither. That does require an extra loop and maybe that is what you were trying to do in your code. The correct code looks like this
do
{
cout << "Vill du spela igen?: j/n?: " << endl;
cin >> spelaigen;
}
while (spelaigen != 'j' && spelaigen != 'J' && spelaigen != 'n' && spelaigen != 'N');
if (spelaigen == 'n' || spelaigen == 'N')
break;
Im having issues on how to make the while loop work on my code (C++), can you please help? I want the user to be asked a question and if the answer is "si" then to execute what I have for the if statements. If answer is no, then skip the while loop and execute the last code. Im getting an error after all the input, just an endless loop of letters.
Any hints on how I can fix it will be very appreciated! Thank you.
int main()
{
int a, b, c, d, total, promedio;
string siNo;
cout << "Ingresar nota 1: ";
cin >> a;
cout <<"Ingrese segunda nota: ";
cin >> b;
cout << "Ingrese tercera nota: ";
cin >> c;
cout << "Ingresar nota 4: ";
cin >> d;
cout<<endl;
cout << "Desea eximirse? ";
cin >> siNo;
total = (a+b+c+d)/4;
promedio = (a+b+c)/3;
while (siNo != "no"){
if(promedio >= 85){
cout << "Si está eximido, su promedio es: " + promedio;
}
if(promedio < 85){
cout << "No está eximido, su promedio de los 3 parciales es:" + promedio;
}
}
cout << "Su nota final es " + total;
return 0;
}
You haven't given any exit loop statement inside your while loop that is why it is running in infinite loop
while (siNo != "no"){
if(promedio >= 85){
cout << "Si está eximido, su promedio es: " + promedio;
break; // just add this line
}
if(promedio < 85){
cout << "No está eximido, su promedio de los 3 parciales es:" + promedio;
break;
}
}
This is an infinite loop:
while (siNo != "no") {
if(promedio >= 85){
cout << "Si está eximido, su promedio es: " + promedio;
}
if(promedio < 85) {
cout << "No está eximido, su promedio de los 3 parciales es:" + promedio;
}
}
Since nothing changes siNo after the cout statements, it's going to keep evaluating (siNo != "no") to be true.
I don't think a loop is necessary here
// if answer is equal to "si"
if (siNo == "si") {
if(promedio >= 85){
} // continue here
}
// else is not required
// if you don't want to do anything when answer is no
return 0;
A simple if statement will do the trick for ya.
Thank you all for your suggestions and comments, it was definitely easier to use ifs, no need for a while loop. Here is how I solved it:
if (siNo == "si")
{
if(promedio >= 85)
{
cout << "Si está eximido, su promedio es: " << promedio << endl;
cout << "Su nota para el cuarto parcial es: " << promedio << endl;
}
else {
cout << "No está eximido, su promedio de los 3 parciales es:"<< promedio << endl;
}
}
if (siNo == "no")
{
cout << "Ingresar nota 4: ";
cin >> d;
cout << "Su nota final es " << total;
}
return 0;
}
Hey thank you all for your responses. I finally managed to make it work with your tips and using for loops. Here is the code, hope it helps others with same questions:
int main() {
double precios[5];
int cantidades[5];
double precioMasAlto = 0;
int cantidadMinima;
double total = 0;
int codigosProducto[5];
int codigoProducto = 0;
int codCantidadMasBaja = 0;
// 1. ingreso de datos
for (int i = 0; i < 5 ; i++) {
cout << "Ingrese codigo de producto " << i << endl;
cin >> codigosProducto[i];
cout << "Ingresar precio de producto " << i << endl;
cin >> precios[i];
cout << "Ingresar cantidad del producto " << i << endl;
cin>> cantidades[i];
}
cantidadMinima = cantidades[0];
// 2. cual de los productos tiene el precio mas alto
for(int posicion = 0; posicion < 5; posicion++){
if(precios[posicion] > precioMasAlto){
precioMasAlto = precios[posicion];
codigoProducto = codigosProducto[posicion];
}
}
cout << "El producto con mayor precio es el Producto " << codigoProducto << ", cuyo precio es " << precioMasAlto <<endl;
// 3. cual de los productos tiene menor existencias
for(int posicion = 0; posicion < 5; posicion++){
if(cantidades[posicion] < cantidadMinima ){
cantidadMinima = cantidades[posicion];
codigoProducto = codigosProducto[posicion];
}
}
cout << "El producto con menor existencia es el Producto " << codigoProducto << ", con una existencia actual de " << cantidadMinima << endl;
// 4. total de productos
for (int i = 0; i < 5; i++){
total += cantidades[i];
}
cout << "El total de productos x cantidad es " << total;
return 0;
}
I have been coding a program to simulate a roulette of a casino, thing is that every time I try to repeat the game after is finished I want the game to keep going and the money to be the same, so if you have lost money you start with that certain money, here is the code (It's in Spanish but I think it's pretty clear):
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int num, pri, randum, num2, op, num3 = 10000, col = randum, rep, clear;
int main() {
do {
int num4 = op;
cout << "Escoja la opción de la que apostar.\n";
cout << "1 - Apostar a un número. \n2 - Apostar a un color \n";
cout << "Elija opción: ";
cin >> pri;
cout << " \n";
cout << " \n";
switch (pri) {
case 1: {
srand(time(0));
randum = rand() % 37 + 1; //si poner 37 + 1 te va cojer números hasta el 37 no?
if (num4 != 10000) {
cout << "Su saldo actual es " << num3 << " €\n";
} else {
cout << "Su saldo actual es 10000 €\n";
}
cout << "Ha elegido apostar a un número\n";
cout << "Introduzca el dinero que quiere apostar -->\n";
cin >> num;
cout << "Ahora introduzca el número que desee entre el 0 y 36 -->\n";
cin >> num2;
if (num2 == randum) {
op = num3 + num;
cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << op << " €\n";
} else {
op = num3 - num;
cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << op << " €\n";
cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n";
cin >> clear;
if (clear == 1) {} else if (clear == 2) {
cout << "Bien, suerte en la próxima tirada.\n\n";
}
}
break;
}
case 2: {
if (num3 == 10000) {
cout << "Su saldo actual es 10000 €\n";
} else {
cout << "Su saldo actual es " << num3 << " €\n";
}
cout << "Ha elegido apostar a un color\n";
cout << "Introduzca el dinero que quiere apostar -->\n";
cin >> num;
srand(time(0));
randum = rand() % 2 + 1;
cout << "Ahora escoja rojo (1) o negro (2) -->\n";
cin >> col;
if (col == randum) {
op = num3 + num;
cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << op << " €";
} else {
op = num3 - num;
cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << op << " €";
}
cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n";
cin >> clear;
if (clear == 1) {} else if (clear == 2) {
cout << "Bien, suerte en la próxima tirada.\n\n";
}
}
}
} while (clear == 1);
return 0;
}
So, it should be pretty easy to do that.
Initialize the starting amount outside the loop before the betting begins.
At the end of the loop, ask if user wants to bet more.
Would that work for you? Or do you need it to be initialized when you start the code itself? You could use static
I am just changing a few things from your code:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
int money = 10000, bet_amount = 0, clear, pri;
cout << "Su saldo inicial es " << money << " €\n";
do
{
cout << "Escoja la opción de la que apostar.\n";
cout << "1 - Apostar a un número. \n2 - Apostar a un color \n";
cout << "Elija opción: ";
cin >> pri;
cout << " \n";
cout << " \n";
cout << "Introduzca el dinero que quiere apostar -->\n";
cin >> bet_amount;
switch (pri)
{
case 1:
{
int number_chosen = -1, randum;
cout << "Ahora introduzca el número que desee entre el 0 y 36 -->\n";
cin >> number_chosen;
srand(time(0));
randum = rand() % 37; // This will give result in the range 0 - 36
if (randum == number_chosen)
{
money += bet_amount;
cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << money << " €\n";
}
else
{
money -= bet_amount;
cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << money << " €\n";
}
break;
}
case 2:
{
int color = 0, randcol;
cout << "Ahora escoja rojo (1) o negro (2) -->\n";
cin >> color;
srand(time(0));
randcol = rand() % 2 + 1;
if (randcol == color)
{
money += bet_amount;
cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << money << " €\n";
}
else
{
money -= bet_amount;
cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << money << " €\n";
}
break;
}
default:
break;
}
cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n";
cin >> clear;
if (clear == 2)
{
cout << "Bien, suerte en la próxima tirada.\n\n";
}
} while (clear == 1);
cout << "Tu saldo final es " << money << " €\n";
return 0;
}
It took me a while to figure out the code because I had to use google translate
I suggest you store the money into a file Like this :
#include <fstream>
ofstream myfile ("money.txt");
if (myfile.is_open())
{
myfile << "put the money in the bag here";
myfile.close();
}
else cout << "Unable to open file";
And whenever you want to read the value
Use this:
string line;
ifstream myfile ("money.txt");
if (myfile.is_open())
{
getline (myfile,line);
cout << line << '\n';
myfile.close();
}
else cout << "Unable to open file";
I'm new in data structure, right now i'm working on a assignment and don't know what is the problem with this structures. Please need help. I will post a image of these errors.
I don't know what these errors means. What I have to do?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Estructura para tipos de persona.
struct persona {
string nombre;
string direccion;
int numero;
};
persona proveedores[];
persona clientes[];
persona empleados[];
// Estructura para producto.
struct producto {
string nombre;
int numero;
};
producto product[];
// Indice para variables de estructura... para referencia
int NUM_Proveedores,
NUM_Clientes,
NUM_Empleados,
NUM_Producto;
void menuPrincipal() {
cout << "Bienvenido a Apple Inc.\n"
<< "MENU: Que deseas hacer?\n"
<< "1. Entrar Data.\n"
<< "2. Ver data.\n"
<< "3. Salir del programa.\n";
}
void menuData() {
cout << "Bienvenido a Apple Inc.\n"
<< "MENU: Entrada de datos.\n"
<< "1. Entrar Proveedores.\n"
<< "2. Entrar Clientes.\n"
<< "3. Entrar Empleados."
<< "4. Entrar Productos.\n"
<< "5. Salir del programa.\n";
}
int main(){
int choise_MenuPrincipal;
int choise_MenuData;
menuPrincipal(); // call menuPrincipal function
cin >> choise_MenuPrincipal;
if (choise_MenuPrincipal == 1) {
menuData();
cin >> choise_MenuData;
if (choise_MenuData == 1) {
// Proveedores code here
cout << "Cuantidad de proveedores a ingresar: ";
cin >> NUM_Proveedores;
// loop de proveedores
for (int i = 0; i < NUM_Proveedores; i++) {
cout << "Nombre del proveedor " << i++ << ": ";
cin >> proveedores[i].nombre;
cout << "Direccion del proveedor " << i++ << ": ";
cin >> proveedores[i].direccion;
cout << "Numero del proveedor " << i++ << ": ";
cin >> proveedores[i].numero;
}
}
else if (choise_MenuData == 2) {
// Clientes code here
cout << "Cuantidad de clientes a ingresar: ";
cin >> NUM_Clientes;
// loop de clientes
for (int i = 0; i < NUM_Clientes; i++) {
cout << "Nombre del cliente " << i++ << ": ";
cin >> clientes[i].nombre;
cout << "Direccion del cliente " << i++ << ": ";
cin >> clientes[i].direccion;
cout << "Numero del cliente " << i++ << ": ";
cin >> clientes[i].numero;
}
}
else if (choise_MenuData == 3) {
// Empleados code here
cout << "Cantidad de empleados a ingresar: ";
cin >> NUM_Empleados;
// loop de clientes
for (int i = 0; i < NUM_Empleados; i++) {
cout << "Nombre del empleado " << i++ << ": ";
cin >> empleados[i].nombre;
cout << "Direccion del empleado " << i++ << ": ";
cin >> empleados[i].direccion;
cout << "Numero del empleado " << i++ << ": ";
cin >> empleados[i].numero;
}
}
else if (choise_MenuData == 4) {
// Producto code here
cout << "Cantidad de productos a ingresar: ";
cin >> NUM_Producto;
// loop de producto
for (int i = 0; i < NUM_Producto; i++) {
cout << "Nombre del producto " << i++ << ": ";
cin >> product[i].nombre;
cout << "Numero del producto " << i++ << ": ";
cin >> product[i].numero;
}
}
else {
cout << "End Program." << endl;
}
}
else if (choise_MenuPrincipal == 2){
// ver data code here
}
else {
cout << "End Program." << endl;
}
system("Pause");
return 0;
}
The problem is you can't define array like this
persona proveedores[];
The compiler needs to know the size of the array in advance. One solution is change this line to
const size_t MAX_SIZE = 100;
persona proveedores[MAX_SIZE];
...and then do the same with clientes, empleados, product etc.
If you need dynamic size array, use std::vector instead.
The issue is that you have not allocated memory for your structures.
persona proveedores[];
persona clientes[];
persona empleados[];
Later on you are trying to access something you don't have really
cin >> proveedores[i].nombre;
Please allocate your arrays like
persona proveedores[10];
persona clientes[10];
persona empleados[10];
and you'll get rid of compilation issues at least.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm working on a school project, my project is a Cypher and Decypher program that works with Caesar Algorithm.
My program has to have the following characteristics:
The program must give the user the option to initiate again. (Done.)
If the user inputs something wrong, the program must ask the user to imput again. (Done with a bug.)
The user can only input letters and - por spaces. (I only need to add the space thing.)
The letter must be moved 5 places (ie. A = F) (Done.)
The program must consider capital letters. (Done.)
Each time you input a letter the screen must clear. (Done.)
At the end of the program you must be able to see the encrypted or decrypted text. (Needs to finish.)
What I need to know is how to make the program show me the encrypted text, counting all the inputs I have made so far while the program has been running.
And an extra thing is how can I input a whole text sentence and apply the Caesar Encryption, obviously I'd have to change almost all my code but I'd like how to do it.
This is the code I have so far, sorry if the sentences are in Spanish but I am living in Mexico for the moment and my classes are in Spanish. If you need me to translate the text I can gladly do it for you.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(int, char**) {
// Variables.
char l;
int x = 0;
char y = x + l;
bool volverainiciar;
volverainiciar = 1;
while (volverainiciar == 1) {
cout << "Favor de introducir la letra del mensaje que desea codificar."
<< endl;
cin >> l;
cout << " " << endl;
cout << " " << endl;
if ((l >= 'a' && l <= 'u') || (l >= 'A' && l <= 'U')) {
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra " << l << " tiene un codigo ASCII de: " << x + l
<< endl;
y = (l + 5);
cout << "La letra " << l << " encriptado tiene un valor de: " << y
<< endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver a "
"iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
} else if ((l >= 'v' && l <= 'z') || (l >= 'V' && l <= 'Z')) {
switch (l) {
case 'v':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: a" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'w':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: b" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'x':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: c" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'y':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: d" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'z':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: e" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'V':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: A" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'W':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: B" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'X':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: C" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'Y':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: D" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
case 'Z':
cout << "El mensaje a codificar es: " << l;
cout << " " << endl;
cout << " " << endl;
cout << "La letra u tiene un codigo ASCII de: " << x + l
<< endl;
cout << "La letra " << l
<< " encriptado tiene un valor de: E" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Se limpiara la pantalla..." << endl;
system("pause");
system("cls");
cout << " Desea volver a iniciar?" << endl;
cout << " " << endl;
cout << " Para volver a iniciar (1) , para no volver "
"a iniciar (0)" << endl;
cout << " " << endl;
cout << "Volver a iniciar: ";
cin >> volverainiciar;
cout << " " << endl;
cout << " " << endl;
break;
}
} else {
cout << "Ese simbolo no es valido, favor de introducir uno valido."
<< endl;
cin >> l;
cout << " " << endl;
cout << " " << endl;
continue;
}
}
cout << "Gracias por usar el encriptador/desencriptador." << endl;
exit;
return 0;
}
If you have any suggestions I'll gladly read them too :)
And sorry for any misspellings my english is not perfect because almost my whole life I've been living here...
I hate to trash your really long program, but it was annoying.
Try this:
// Given the input character is in x.
if (std::isalpha(x))
{
if (std::islower(x))
{
y = (x - 'a'); // Convert to a number.
y = y + 5; // Left shift by 5
y = y % 26; // Modulo arithmetic for all letters in alphabet
y = y + 'a'; // Convert back to character.
}
else
{
y = (x - 'A'); // Convert to a number.
y = y + 5; // Left shift by 5
y = y % 26; // Modulo arithmetic for all letters in alphabet
y = y + 'A'; // Convert back to character.
}
}
One of my pet peeves is duplicate code. Although there is duplicate code above, I've reduced the amount of duplication in your code. Feel free to add all your cout statements in the code above.
By the way, you can "block write" your data to cout, if the data doesn't use variables.
Example:
static const char answer_text[] =
"\n"
"\n"
"La letra u tiene un codigo ASCII de: ";
//...
cout.write(answer_text, sizeof(answer_text) - 1);
This will allow you to use the cout.write statement everywhere you need to use the same text. Less typing, less lines, less probability of injecting a defect.