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;
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 want to know why, when I print the instruction iscntrl, the return value is always 2?
I also want to know why the result of the isalpha statement is 1024.
For example:
#include <iostream>
using namespace std;
int main()
{
char lettera = 'c';
char numero = '1';
isalpha(lettera)? cout << lettera << " è un carattere!" : cout << lettera << " non è un carattere!";
isalpha(numero)? cout << numero << " è un carattere!" : cout << numero << " non è un carattere!";
cout << endl << isalpha(lettera) << endl; //print 1024
cout << isalpha(numero) << endl; //print 0
cout << iscntrl(numero) << endl; //print 0
cout << iscntrl(1) << endl; //print 2
}
The iscntrl() function return value:
A value different from zero (i.e., true) if indeed c is an alphabetic
letter. Zero (i.e., false) otherwise.
The isalpha() function return value:
A value different from zero (i.e., true) if indeed c is a control
character. Zero (i.e., false) otherwise.
So, it returns non-zero value (not 1) when the condition is true. So that's intentional.
Also, a tiny note:
isalpha(lettera)? cout << lettera << " è un carattere!" : cout << lettera << " non è un carattere!";
isalpha(numero)? cout << numero << " è un carattere!" : cout << numero << " non è un carattere!";
Those two statements are very similar, so you should make a function:
inline void printmsg(char ch)
{
std::cout << ch << (isalpha(ch) ? "" : " non") << " è un carattere!";
}
and call it:
printmsg(lettera);
printmsg(numero);
In class we have to make a code that give a color etc etc, I am very bad to explain things (I'm french).
So the problem is that in my code (under), I would like to prevent the user to input a number up to 255, but it actually don't work, how can I fix it ;p
Thanks all
#include <iostream>
using namespace std;
//Déclarations :
struct Srgb
{
unsigned char r ;
unsigned char g;
unsigned char b;
};
union UColor
{
unsigned int val;
Srgb components;
unsigned char tabCol[3];
};
int valeur_unique;
int main()
{
int entier;
UColor rgb1;
int choix;
cout << "Vous preferez entrer valeur unique(1) ou RGB(2) ? : " << endl;
cin >> choix;
switch (choix) {
case 1: //Valeur unique
cout << " Entrez la valeur totale : " << endl;
cin >> valeur_unique;
break; //CASE VALEUR UNIQUE
case 2: //RGB
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// ROUGE
cout << " Entrez la valeur du rouge :" << endl;
cin >> entier;
rgb1.components.r = entier;
while (rgb1.components.r >= 256) {
cout << "Rouge ne peux pas etre superieur a 255" << endl;
cout << " Entrez la valeur du rouge : " << endl;
cin >> entier;
rgb1.components.r = entier;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// VERT
cout << " Entrez la valeur du vert :" << endl;
cin >> entier;
rgb1.components.g = entier;
while (rgb1.components.g >= 256) {
cout << "Vert ne peux pas etre superieur a 255" << endl;
cout << " Entrez la valeur du vert : " << endl;
cin >> entier;
rgb1.components.g = entier;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BLEU
cout << " Entrez la valeur du bleu :" << endl;
cin >> entier;
rgb1.components.b = entier;
while (rgb1.components.b >= 256) {
cout << "Bleu ne peux pas etre superieur a 255" << endl;
cout << " Entrez la valeur du bleu : " << endl;
cin >> entier;
rgb1.components.b = entier;
}
cout << (int) rgb1.components.r << endl;
cout << (int)rgb1.components.g << endl;
cout << (int)rgb1.components.b<< endl;
break; //CASE RGB
}
}
Sorry if I don't properly use the thing.
So As you can see, with the while loop I try to do that if the user enter something sup or equals to 256 it still ask to enter something, but it don't, why ?
Check if the input is valid before assigning into your char!
If you assign into your char immediately and then check to see if the char is under 256, it will always be!
You need to check the int before you assign (and ever better, check that it's in the range [0, 255] like you want):
cout << " Entrez la valeur du rouge :" << endl;
cin >> entier;
while (entier < 0 || entier > 255) {
cout << "Rouge ne peux pas etre superieur a 255" << endl;
cout << " Entrez la valeur du rouge : " << endl;
cin >> entier;
}
// Only assign after we know entier is good!
rgb1.components.r = entier;
my code stop working if the user made the 4-5-6 choice in my c++ app
i tried restart it many times and it not work
i rewrite it too and is not working
i speak french so many things is in french sorry
//sorry im french i translate the most importants things
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
std::cout << R"(Bienvenue dans le convertisseur universel L&A industries)";
int e, x, y;
double z, a, b;
std::cout << "\nthere is the choices de of conversions:\n\n";
std::cout << " 1.Tax 2.Temperature 3.Longueur \n";
std::cout << " 4.speed 5.Mass 6.Frequency\n\n";
std::cout << "Quelle conversion voulez-vous faire ?";
std::cin >> x;
if (x == 1) {
std::cout << "Vous avez choisi : Taxes\n";
x = 1.15;
enter code here
std::cout << "Entrez l'argent($): ";
std::cin >> z;
a = z * 1.15;
std::cout << "Avec les taxes votre somme reviens a : " << a << "\n";
if (z == 0) {
std::cout << "Erreur";
}
}
else if (x == 2) {
std::cout << "Quel unite de mesure voulez-vous utiliser? 1.Celsius > Farenheit 2.Farenheit > Celsius :\n";
std::cin >> e;
if (e == 1) {
std::cout << "Entrez votre Temperature en celsius: ";
std::cin >> b;
y = b * 9 / 5 + 32;
std::cout << "Votre Temperature est de : " << y << " °F\n";
}
else if (e == 2) {
std::cout << "Entrez votre Temperature en Farenheit: ";
std::cin >> x;
y = (x - 32) * 5 / 9;
std::cout << "Votre Temperature est de : " << y << " °C\n";
}
}
else if (x == 3) {
std::cout << "Quel unite de mesure voulez-vous utiliser : 1.Metre vers pied 2.Pieds vers metre\n";
std::cin >> e;
if (e == 1) {
std::cout << "Entrez votre longueur en metres :";
std::cin >> x;
y = x * 3.281;
std::cout << "Votre longueur est de : " << y << " pi \n";
}
else if (e == 2) {
std::cout << "Entrez votre longueur en Pieds :";
std::cin >> x;
y = x / 3.281;
std::cout << "Votre longueur est de : " << y << " m \n";
}
else if (x == 4)
{
std::cout << "Entrez votre longueur en Pieds :";
std::cin >> x;
y = x / 3.281;
std::cout << "Votre longueur est de : " << y << " m \n";
}
while (true) {
system("pause");
}
return 0;
}
}
'
the program stop if i answer 4-5-6
number is the value we attribute to "X"
...................................................................................................................................................................................................................................................................................................................
Your code doesn't seem to handle choices 5 or 6 at all. It attempts to handle choice x==4 but fails as you're missing a closing brace for the x==3 option.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
std::cout << R"(Bienvenue dans le convertisseur universel L&A industries)";
int e, x, y;
double z, a, b;
std::cout << "\nthere is the choices de of conversions:\n\n";
std::cout << " 1.Tax 2.Temperature 3.Longueur \n";
std::cout << " 4.speed 5.Mass 6.Frequency\n\n";
std::cout << "Quelle conversion voulez-vous faire ?";
std::cin >> x;
if (x == 1) {
std::cout << "Vous avez choisi : Taxes\n";
x = 1.15; //This should be a double since you have a decimal
//enter code here
std::cout << "Entrez l'argent($): ";
std::cin >> z;
a = z * 1.15;
std::cout << "Avec les taxes votre somme reviens a : " << a << "\n"; //
if (z == 0)
{
std::cout << "Erreur";
}
}
else if (x == 2)
{
std::cout << "Quel unite de mesure voulez-vous utiliser? 1.Celsius > Farenheit 2.Farenheit > Celsius :\n";
std::cin >> e;
if (e == 1) {
std::cout << "Entrez votre Temperature en celsius: ";
std::cin >> b;
y = b * 9 / 5 + 32;
std::cout << "Votre Temperature est de : " << y << " °F\n";
}
else if (e == 2) {
std::cout << "Entrez votre Temperature en Farenheit: ";
std::cin >> x;
y = (x - 32) * 5 / 9;
std::cout << "Votre Temperature est de : " << y << " °C\n";
}
}
else if (x == 3) //Vous n'avez jamais fermé cette boucle - Voir ci-dessous
{
std::cout << "Quel unite de mesure voulez-vous utiliser : 1.Metre vers pied 2.Pieds vers metre\n";
std::cin >> e;
if (e == 1) {
std::cout << "Entrez votre longueur en metres :";
std::cin >> x;
y = x * 3.281;
std::cout << "Votre longueur est de : " << y << " pi \n";
}
else if (e == 2)
{
std::cout << "Entrez votre longueur en Pieds :";
std::cin >> x;
y = x / 3.281;
std::cout << "Votre longueur est de : " << y << " m \n";
}
else if (x == 4)
{
std::cout << "Entrez votre longueur en Pieds :";
std::cin >> x;
y = x / 3.281;
std::cout << "Votre longueur est de : " << y << " m \n";
}
} //Vous avez besoin de ça ici
//Vous n'en avez pas besoin ici. Pas de boucle en boucle - boucle fermée
// while (true) { - DELETE
system("pause");
// } - DELETE
return 0;
}