简体   繁体   中英

extracting int into array from long long in c

I'm new to programming and have no experience with arrays of undefined length. I want to extract specific numbers from a long long that is generated by user input (because I failed to do so with a char). The best result would be for me that it would end up in an array with each digit its own int so that i can run loops and do math with them.

Say that i want to get the 20th digit from the right, with the amount of digits that the user put in GetLongLong unknown, this is what my code looks like:

int spec20 = (digits / 10000000000000000000) % 10;

How can I make this simpler and use an array to store specific digits?

you can do this:

char str[100]; // your number should most probably fit
sprintf(str,"%lld",digits);

then str will contain string representation of your number, and you can find 20th element from the right (starting to count from 1) like this (not the only way for sure).

int d_len = strlen(str);
int the_20th_pos = (d_len>20? d_len-20: -1); // take care of numbers less than 20 digits
int the_20th = (int)(the_20th_pos<0? 0: str[d_len-the_20th_pos]-'0'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM