¿Cómo separar los dígitos de un número en C ++?
Pregunta
Estoy tratando de encontrar una manera de obtener 5 dígitos por separado de un número entero.
cin >> option; // Option to enter a number(don't worry about this)
if (option == 1) // The option(don't worry)
{
cout << " enter 5 digit key 0 to 9 \n";
readin(key); // The input number that needs the digits to be separated
}
El código anterior solo ingresa el número, pero quiero separar los dígitos de alguna manera ... pero ¿cómo?
Solución
algo como esto:
// handle negative values
key = ABS(key);
while(key > 0)
{
// get the digit in the one's place (example: 12345 % 10 is 5)
int digit = key % 10;
// remove the digit in the one's place
key /= 10;
}
Otros consejos
¿Por qué no leer cada entrada individualmente y manejarlas individualmente?
es decir
cout<< " enter 5 digit key 0 to 9 \n";
char str[5];
cin.get(str, 5);
for (int i = 0; i < 5; ++i)
{
//do something with str[i];
}
Puede usar el siguiente fragmento de código, separará los dígitos en orden inverso enwhile
círculo.
int i;
cin >> i;
while (i%10 != 0)
{
cout << i%10 << endl;
i = i/10;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
size_t len = str.size();
len = len > 5 ? 5 : len;
for (size_t i=0; i<len; ++i)
{
cout << "digit " << i << " is: " << (str[i] - '0') << endl;
}
return 0;
}
Lo hago de esta manera
El método de bucle While solo se encargará de los dígitos sin ceros.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow