+ 1
Store each digit separately in an array
Hi all! Ley's say I want the user to enter a 4-digit code (eg 1572). Then I want to take each digit and store it separately in array. How can I "pick" each digit from that int (or string, if I have to) and store it as an INT in an array (I need it as an INT because I want to use it later for calculations). Thanks in advance! 😊
3 ответов
+ 9
#include <iostream>
using namespace std;
int main() {
int i = 1234;
int x = i, c = 0;
while(x != 0)
{
++c;
x /= 10;
}
int v = c;
int j [c];
while(i != 0)
{
j[--c] = i % 10;
i /= 10;
}
for(int y = 0; y < v; y++)
cout << j[y] << endl;
}
+ 5
You need to extract the digits and then store it in an array.
For that write a extract digits function.
How to write one? divide the number(ex 1572) by 10. quotient is 157 and remainder is 2. store 2 in the array. Now divide the previous quotient (157) by 10. quotient is 15 and remainder is 7. store 7 in the array. repeat this and finally you get the array of extracted digits.
+ 2
Added a try-except in case the user pressed something else...
you can change it to a message
https://code.sololearn.com/cvmESkH8jxYm/?ref=app