If you make the percentage the last thing you ask, everything works fine, with and without a symbol of %
cout << "De cuanto es el deposito de combustible de vuestro coche? \n";
cin >> litrosDeposito;
cout << "Cuantos KM haces con un litro de combustible? \n";
cin >> consumoCoche;
cout << "Y cuanto porcentaje os queda? 100%, 75%, 50% o 25%? \n";
cin >> porcentajeRestante;
Why does this happen? The input flow ( std::cin
) when reading in numeric values reads numbers until it finds a non-numeric data, at which moment it stops reading. This means that reading 12%
the reading pointer stays after 2
:
Before (read in porcentajeRestante
: nothing):
Posición del búfer: | 0 | 1 | 2 |
+---+---+---+
Datos del búfer: | 1 | 2 | % |
+---+---+---+
Puntero de lectura: | ^ | | |
After (read in porcentajeRestante
: 12
):
Posición del búfer: | 0 | 1 | 2 |
+---+---+---+
Datos del búfer: | 1 | 2 | % |
+---+---+---+
Puntero de lectura: | | | ^ |
When you try to read the following data (suppose that it is 20
), the first thing you find is the %
that since it is not a numerical value, it does not read:
Before (read in consumoCoche
: nothing):
Posición del búfer: | 0 | 1 | 2 | 3 | 4 |
+---+---+---+---+---+
Datos del búfer: | 1 | 2 | % | 2 | 0 |
+---+---+---+---+---+
Puntero de lectura: | | | ^ | | |
After (read in consumoCoche
: nothing , %
is not a number):
Posición del búfer: | 0 | 1 | 2 | 3 | 4 |
+---+---+---+---+---+
Datos del búfer: | 1 | 2 | % | 2 | 0 |
+---+---+---+---+---+
Puntero de lectura: | | | | ^ | |
To avoid the problem, you can change the order of data collection by leaving the percentage for the last or, after reading the percentage, clean the buffer:
cout << "De cuanto es el deposito de combustible de vuestro coche? \n";
cin >> litrosDeposito;
cout << "Y cuanto porcentaje os queda? 100%, 75%, 50% o 25%? \n";
cin >> porcentajeRestante;
if (cin.peek() == '%') // Si el siguiente dato es un '%', lo ignoramos.
cin.ignore(1);
cout << "Cuantos KM haces con un litro de combustible? \n";
cin >> consumoCoche;