Why does it always return true? Even when i put 'n' in my char choice.
The same thing for my do-while loop.
is there something wrong with my if /do/while fonctions?
void LigueHockey::New()
{
char choice;
cout << "Entrez l'histoire de la ligue : ";
getline(cin,histoire);
cout << "\nQuel est la couleur de la ligue : ";
getline(cin,couleur);
cout << "\nEntrez la date d'aujourd'hui(JJ/MM/YYYY) : ";
cin.getline(creation.jour,sizeof(creation.jour),'/');
cin.getline(creation.mois,sizeof(creation.mois),'/');
cin.getline(creation.annee,sizeof(creation.annee));
cout << "\nEst-ce que le club a gagner un titre? (Y/N) :";
cin >> choice;
cin.ignore(); // to skip the endline
if (choice = 'Y')
{
do
{
cout << "\nNom de la coupe/titre : ";
cin.getline(records.coupe,sizeof(records.coupe));
cout << "\nQuand a-t-il ete remporter? (JJ/MM/YYYY) : ";
cin.getline(records.dateRemp.jour,sizeof(records.dateRemp.jour),'/');
cin.getline(records.dateRemp.mois,sizeof(records.dateRemp.mois),'/');
cin.getline(records.dateRemp.annee,sizeof(records.dateRemp.annee));
cout << "\nVoulez-vous ajouter un autre coupe/titre? : ";
cin >> choice;
cin.ignore();
}
while ( choice = 'Y');
}
}
if (choice = 'Y') is an assignment, not an equality check. You need if (choice == 'Y')
Please use == in your if condition
example :
if (choice == 'Y')
Thanks
Javid
Related
I currently have this and I can't seem to make my else work so the whole program doesn't limit the input successfully. (Sorry for my English I speak French).
cout << "Veuillez entrer votre nombre de 6 chiffres : ";
cin >> val;
if (val < 100000);
{
cout << "Erreur! Veuillez recommencez avec un nombre a 6 chiffres. " << endl << endl;
return main();
}
if (val > 999999);
{
cout << "Erreur! Veuillez recommencez avec un nombre a 6 chiffres. " << endl << endl;
return main();
}
else
if
{
nb1 = val / 100000 % 10;
cout << nb1;
}
Firstly, a semicolon between the ) and { of an if statement creates an empty if statement body, followed by an unconditional block, which is not what you want.
To check if a number has more than a certain number of digits, try comparing against negative 999999 instead.
The code should be made shorter by using logical operators instead of 2 separate if statements.
Lastly, you should not recurse into main(). Use goto instead.
Corrected Code:
retry:
cout << "Veuillez entrer votre nombre de 6 chiffres : ";
cin >> val;
if (val < -999999 || val > 999999) // Note the ; has been removed
{
cout << "Erreur! Veuillez recommencez avec un nombre a 6 chiffres. " << endl << endl;
goto retry;
}
nb1 = val / 100000 % 10;
cout << nb1;
Alternatively, you could use the abs() function (use #include <cstdlib>):
if (abs(val) > 999999)
{
cout << "Erreur! Veuillez recommencez avec un nombre a 6 chiffres. " << endl << endl;
goto retry:
}
nb1 = val / 100000 % 10;
cout << nb1;
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 cant use the s1[40] for the second time or longer in the circle and it's always full,
and cin.getline(s1,40)
is ignored at later times
char s1[40], ans = 'y';
while (ans == 'y')
{
system("cls");
cout << "\n Enter a sentence : ";
cin.getline(s1, 40);
fflush(stdin);
cout << "\n________________________________________\n\n Again?(y/n)";
cin >> ans;
fflush(stdin);
};
cin >> ans; will actually not remove eol so next getline will read an empty line and cin >> ans; will read first symbol of line. You should make ans an array as well use getline twice:
for(;;)
{
char s1[40]{};
system("cls");
cout << "\n Enter a sentence : ";
cin.getline(s1, 40);
fflush(stdin);
if(cin.fail() or cin.bad())
{
cout << "fail" << endl;
break;
}
cout << "\n________________________________________\n\n Again?(y/n)";
char ans[2]{};
cin.getline(ans, 2);
fflush(stdin);
if(cin.fail() or cin.bad())
{
cout << "fail" << endl;
break;
}
if(0 != strcmp("y", ans))
{
break;
}
}
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.
So im getting a compiling error that says:
12 C:\Dev-Cpp\login.cpp expected unqualified-id before "while"
12 C:\Dev-Cpp\login.cpp expected ,' or;' before "while"
C:\Dev-Cpp\Makefile.win [Build Error] [login.o] Error 1
this is my code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string username;
string password;
int attemptCount = 0;
}
while ( attemptCount < 3 )
{
cout << "Enter your username: " << endl;
cin >> username;
cout << "Enter your password: " << endl;
cin >> password;
if ( username != "Invitado" && password != "abel" )
{
int choice;
bool gameOn = true;
while (gameOn != false){
cout << "\n\n\n\n\n\n\n\n\n\n\n";
cout << " 1 - Inicia el juego.\n\n";
cout << " 2 - Modo Historia.\n\n";
cout << " 3 - Ayuda.\n\n";
cout << " 4 - Salir.\n\n";
cout << "\n\n\nElige tu opcion\n\n\n ";
cin >> choice;
switch (choice)
{
case 1:
cout << "\n\n\n\nBienvenido al juego...!\n";
// rest of code here
break;
case 2:
cout << "\n\n\n Este es el progreso hasta el momento\n";
// rest of code here
break;
case 3:
cout << "\n\n\n\n\n\n\n\nPara ayuda, por favor visite www.blabla.com!\n";
// rest of code here
break;
case 4:
cout << "\n\n\nFin del programa.\n";
gameOn = false;
break;
default:
cout << "\n\n\nNo es una opcion valida. \n";
cout << "\n\n\nElige de nuevo.\n";
cin >> choice;
break;
}
}
return 0;
}