0

I want to get the each digit (like units digit, hundreds digit...) of an integer, So I write a code. why it always gets wrong?

sorry I am not good at english. here's my code: #include <iostream> using namespace std; int main() { int X; int a[] = {}; int i = 0; cin >> X; for(;X != 0;i++){ a[i] = X % 10; X = X /10; cout << a[i]; } return 0; }

16th Oct 2019, 8:08 AM
tita Y.H.
tita Y.H. - avatar
2 Respostas
+ 2
You first need to declare array with it's size specified. int a[32]; //can store 32 elements syntax: datatype array_name[size]; int a[]={} means you are not specifying size explicitly. Therefore number of elements that array can store is limited to number of elements with which it was initialized , here 0. {} no elements in curly braces so it can store only 0 elemements. you can't later increase its size, arrays are not resizeable. C++ won't check for array bounds and let you use any index you wan't so be carefull. either specify size of array or you can try with std vector instead of array. https://en.cppreference.com/w/cpp/container/vector Good luck.
16th Oct 2019, 8:21 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
🇮🇳Omkar🕉 Thank you very much! I've thought for this since yesterday, now I success!!
16th Oct 2019, 9:22 AM
tita Y.H.
tita Y.H. - avatar