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.
Related
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 making a code where users can type in numbers that will be stored in an array which is inside a struct. However, sometimes, the value that I input is not the same as the one that is stored/display. This problem is not very consistent. For example, when I input 10, it could either be shown as: 6384644, 6382852, or actually 10. I am very confused for this, I've tried changing the array data type using int, long, and double, but to no avail.
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
int n,x,totalAge = 0,maxAge = 0,avgAge = 0,maxGoals = 0,bestPlayer = 0, oldest = 0;
cout << "Input the number of players: ";
cin >> n;
cout << "Input the number of games: ";
cin >> x;
struct players {
string name;
string currTeam;
int shirtn;
int age;
float height;
float weight;
int totalGoals;
long goals[];
};
players goals[x];
players playerList[n];
for (int i = 0; i < n; i++) {
cout << "Player " << (i+1) << endl;
cout << "Input player's name: ";
cin.ignore();
getline (cin, playerList[i].name);
cout << "Input player's current team: ";
getline (cin, playerList[i].currTeam);
cout << "Input player's shirt number: ";
cin >> playerList[i].shirtn;
cout << "Input player's age: ";
cin >> playerList[i].age;
cout << "Input player's height (m): ";
cin >> playerList[i].height;
cout << "Input player's weight (kg): ";
cin >> playerList[i].weight;
cout << endl;
for (int a = 0; a < x; a++) {
playerList[i].goals[a] = 0;
playerList[i].totalGoals = 0;
}
for (int a = 0; a < x; a++) {
cout << "Game " << (a+1) << "'s number of goals: ";
cin >> playerList[i].goals[a];
playerList[i].totalGoals += playerList[i].goals[a];
}
if (playerList[i].totalGoals > maxGoals) {
maxGoals = playerList[i].totalGoals;
bestPlayer = i;
}
if (playerList[i].age > maxAge) {
maxAge = playerList[i].age;
oldest = i;
}
totalAge += playerList[i].age;
cout << endl;
}
cout << endl;
for (int i = 0; i < n; i++) {
cout << playerList[i].name << endl;
cout << "--------------------" << endl;
cout << "Current team: " << playerList[i].currTeam << endl;
cout << "Shirt Number: " << playerList[i].shirtn << endl;
cout << "Age: " << playerList[i].age << endl;
cout << "Height: " << playerList[i].height << " m" << endl;
cout << "Weight: " << playerList[i].weight << " kg" << endl;
cout << endl;
for (int a = 0; a < x; a++) {
cout << "Game " << (a+1) << "'s number of goals: " << playerList[i].goals[a] << endl;
}
cout << endl << endl;
}
avgAge = totalAge / n;
cout << "Average age of players: " << avgAge << endl;
cout << "Oldest Player: " << playerList[oldest].name << " (" << maxAge << ") ";
cout << "Player who got the most goals: " << playerList[bestPlayer].name << ", shirt number: " << playerList[bestPlayer].shirtn << ". With total goals of: " << playerList[bestPlayer].totalGoals << endl;
}
Your code's corrected version would be this:
#include<string>
#include<iostream>
#include<vector> //for vector
using namespace std;
struct players {
string name;
string currTeam;
int shirtn;
int age;
float height;
float weight;
int totalGoals;
vector<long> goals; //used vector instead of array
};
int main () {
int N, X;
int totalAge = 0, maxAge = 0, avgAge = 0, maxGoals = 0, bestPlayer = 0, oldest = 0;
cout << "Input the number of players: ";
cin >> N;
cout << "Input the number of games: ";
cin >> X;
players player[X];
for (int i = 0; i < N; i++) {
cout << "Player " << (i+1) << endl;
cout << "Input player's name: ";
cin>>player[i].name;
cout << "Input player's current team: ";
cin>>player[i].currTeam;
cout << "Input player's shirt number: ";
cin >> player[i].shirtn;
cout << "Input player's age: ";
cin >> player[i].age;
cout << "Input player's height (m): ";
cin >> player[i].height;
cout << "Input player's weight (kg): ";
cin >> player[i].weight;
cout << endl;
player[i].totalGoals = 0;
for (int a = 0; a < X; a++) {
long G;
cout << "Game " << (a+1) << "'s number of goals: ";
cin >> G;
player[i].goals.push_back(G);
player[i].totalGoals += G;
}
if (player[i].totalGoals > maxGoals) {
maxGoals = player[i].totalGoals;
bestPlayer = i;
}
if (player[i].age > maxAge) {
maxAge = player[i].age;
oldest = i;
}
totalAge += player[i].age;
cout << endl;
}
cout << endl;
for (int i = 0; i < N; i++) {
cout << player[i].name << endl;
cout << "--------------------" << endl;
cout << "Current team: " << player[i].currTeam << endl;
cout << "Shirt Number: " << player[i].shirtn << endl;
cout << "Age: " << player[i].age << endl;
cout << "Height: " << player[i].height << " m" << endl;
cout << "Weight: " << player[i].weight << " kg" << endl;
cout << endl;
for (int a = 0; a < X; a++) {
cout << "Game " << (a+1) << "'s number of goals: " << player[i].goals[a] << endl;
}
cout << endl << endl;
}
avgAge = totalAge / N;
cout << "Average age of players: " << avgAge << endl;
cout << "Oldest Player: " << player[oldest].name << " (" << maxAge << ") ";
cout << "Player who got the most goals: " << player[bestPlayer].name << ", shirt number: " << player[bestPlayer].shirtn << ". With total goals of: " << player[bestPlayer].totalGoals << endl;
return 0;
}
I would like some help with the following code/agenda, every time you edit/delete the agenda and index, it adds an additional "endl;" to "Agenda.txt" and since there is a new line without a index reference, the "Index.txt" saves a "-858993460" as recorded number caused from the new empty line in the agenda caused by editing the file, if you add contacts works fine. The code is basically in spanish but I commented main instructions. Please help!
#include <conio.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <math.h>
using namespace std;
struct estudiantes
{
int telefono;
char nombre[50];
};
estudiantes contacto[100];
int main()
{
int opciones, i;
ifstream readagenda, readindex;
do
{
system("cls");
cout << "Elige opcion a ejecutar" << endl;
cout << "1. Verificar agenda de contactos actual" << endl; //view current agenda
cout << "2. Agregar contactos" << endl; //Add contact numbers
cout << "3. Editar contactos" << endl; //Edit contacts
cout << "4. Eliminar contactos" << endl; //Erase contacts
cout << "5. Terminar Programa" << endl; //End program
cout << "Ingrese # opcion a elegir: ";
cin >> opciones;
switch (opciones)
{
case 1:
{
char linea[100];
cout << endl;
readagenda.open("Agenda.txt", ios::in);
if (readagenda.fail())
{
cout << "No se puede abrir el archivo, ingresa contactos para crear una agenda" << endl;
}
else
{
do
{
readagenda.getline(linea, sizeof(linea));
cout << linea << endl;
} while (!readagenda.eof());
}
readagenda.close();
system("Pause");
break;
}
case 2:
{
ofstream add, index;
int contactos;
cout << "\nIngrese Cantidad de contactos a guardar : ";//how many contacts are you going to save?
cin >> contactos;
for (int i = 1; i <= contactos; i++)
{
cout << "Ingrese Telefono No. " << i << " : ";//phone number
cin >> contacto[i].telefono;
cin.ignore(256, '\n');
cout << "Ingrese Nombre " << i << " : ";//full name
cin.getline(contacto[i].nombre, sizeof(contacto[i].nombre), '\n');
}
add.open("Agenda.txt", ios::app);
if (add.fail())
{
cout << "\nNo se puede crear el archivo" << endl;
exit(1);
}
for (int i = 1; i <= contactos; i++)
{
add << contacto[i].telefono << " - " << contacto[i].nombre << endl;
}
add.close();
index.open("Index.txt", ios::app);
if (index.fail())
{
cout << "\nNo se puede crear el archivo" << endl;
exit(1);
}
for (int i = 1; i <= contactos; i++)
{
index << contacto[i].telefono << endl;
}
index.close();
cout << "\nContacto agregado exitosamente...";//contact added
system("pause");
break;
}
case 3:
{
int modificar, readnum[100];
char newname[100], readcon[100];
i = 0;
bool encontrado = false;
cout << "\nIngrese No. telefono de contacto a modificar: ";//contact to modify
cin >> modificar;
cin.ignore(256, '\n');
cout << "Ingrese nuevo nombre de contacto: "; //new contact name
cin.getline(newname, sizeof(newname), '\n');
ofstream numerosmodtemp;
readindex.open("Index.txt", ios::in); // opens index
readagenda.open("Agenda.txt", ios::in); // opens agenda
numerosmodtemp.open("numerosmodtemp.txt", ios::app); //creates temp file
if (readagenda.fail() || readindex.fail())
{
cout << "\nNo se puede abrir el archivo, ingresa contactos para crear una agenda" << endl;
}
else
{
do
{
readagenda.getline(readcon, sizeof(readcon)); // reads agenda
readindex >> readnum[i]; // reads index
if (readnum[i] == modificar)
{
encontrado = true;
numerosmodtemp << modificar << " - " << newname << endl;//adds new contact info
}
else
{
numerosmodtemp << readcon << endl; // uses regular agenda
}
i++;
} while (!readindex.eof());
numerosmodtemp.close();
readindex.close();
readagenda.close();
if (encontrado == true)
{
cout << "\nContacto modificado exitosamente..."; // contact edited
system("pause");
}
else
{
cout << "\nContacto no ha sido encontrado..."; //contact not found
system("pause");
}
remove("Agenda.txt");
rename("numerosmodtemp.txt", "Agenda.txt");
break;
}
break;
}
case 4:
{
int borrar, readn[100];
char readc[100];
i = 0;
bool encontrado = false;
cout << "\nIngrese No. telefono de contacto a eliminar: ";//number of contact to erase
cin >> borrar;
ofstream numerosborrados, numerosdeltemp, numerostemp;
readindex.open("Index.txt", ios::in); // opens index
readagenda.open("Agenda.txt", ios::in); // opens agenda
numerosborrados.open("Contactos Borrados.txt", ios::app); // opens erased contacts
numerosdeltemp.open("numerosdeltemp.txt", ios::app); // opens temp index
numerostemp.open("numerostemp.txt", ios::app); // opens temp agenda
if (readagenda.fail() || readindex.fail())
{
cout << "\nNo se puede abrir el archivo, ingresa contactos para crear una agenda" << endl;
}
else
{
do
{
readagenda.getline(readc, sizeof(readc)); // reads contacts
readindex >> readn[i]; // reads index
if (readn[i] == borrar)
{
encontrado = true;
numerosborrados << readc << endl; // adds to erased contacts file
}
else
{
numerostemp << readc << endl; // adds to temp agenda
numerosdeltemp << readn[i] << endl; // adds to temp index
}
i++;
}while (!readindex.eof());
}
numerosborrados.close();
numerostemp.close();
numerosdeltemp.close();
readindex.close();
readagenda.close();
if (encontrado == true)
{
cout << "\nContacto eliminado exitosamente...";// contact erased
system("pause");
}
else
{
cout << "\nContacto no ha sido encontrado..."; //contact not found
system("pause");
}
remove("Agenda.txt");
remove("Index.txt");
rename("numerosdeltemp.txt", "Index.txt");
rename("numerostemp.txt", "Agenda.txt");
break;
}
case 5:
{
cout << "\nPrograma terminado, "; // End program
system("pause");
break;
}
default:
{
cout << "\nEsta opcion no esta disponible, "; // not available
system("pause");
break;
}
}
} while (opciones != 5);
}
i'm very new in programming, i have this big code, but when i try to print the data never prints the string variable, can you help?
this is just for
i use "goto" just for practicall reassons.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class producto
{
public:
int id;
string nombre;
string descripcion;
int precio;
void registrar();
void ver();
};
void producto::registrar()
{
cout << "Codigo:" << endl;
cin >> id;
cin.ignore();
cout << "Nombre del producto:" << endl;
getline(cin, nombre);
cout << "Descripcion del producto:" << endl;
getline(cin, descripcion);
cout << "Precio:" << endl;
cin >> precio;
}
void producto::ver()
{
cout << "ID del producto:";
cout << id << endl;
cout << "Nombre del producto:" << endl;
cout << nombre;
cout << "Descripcion del producto:";
cout << descripcion<<endl;
cout << "Precio:";
cout << "$" << precio << endl;
}
int main()
{
menu1:
int menu;
producto cosa;
cout << "************************" << endl;
cout << "1.- Registrar Producto" << endl;
cout << "2.- Ver Producto" << endl;
cout << "************************" << endl;
cin >> menu;
cin.ignore();
switch (menu)
{
case 1:
cout << "INGRESE PRODUCTO NUEVO:\nPresione enter para continuar" << endl;
cin.ignore();
system("cls");
cosa.registrar();
cin.ignore();
break;
case 2:
cosa.ver();
cout << "Presione enter para regresar al menu principal." << endl;
cin.ignore();
break;
}
goto menu1;
return 0;
}
Edit
Here is the int main
The use of goto is not recommended and considered a very bad practice even for a beginner. If you are begining in C++, following best practice is the best way to begin. The goto is supported in C/C++ only for backward compatibility.
For your issue try to use a loop instead of a goto.
int main()
{
//Condition to show the menu or exit
bool bContinue = true;
producto cosa;
do{
int menu;
cout << "************************" << endl;
cout << "1.- Registrar Producto" << endl;
cout << "2.- Ver Producto" << endl;
cout << "3.- Exit" << endl;
cout << "************************" << endl;
cin >> menu;
cin.ignore();
switch (menu)
{
case 1:
cout << "INGRESE PRODUCTO NUEVO:\nPresione enter para continuar" << endl;
cin.ignore();
system("cls");
cosa.registrar();
cin.ignore();
break;
case 2:
cosa.ver();
cout << "Presione enter para regresar al menu principal." << endl;
cin.ignore();
break;
case 3:
bContinue = false;
break;
}
}while(bContinue)
return 0;
}
Like this way, your issue will be fixed and you learn a better way to do it.