I came from python and it was easy to get the middle digit of an integer, for example, from 897 I want the 9:
>>> num = 897
>>> num2 = int(str(num)[1])
>>> num2
9
But how i can do this on C? It's so difficult to convert into string...
I came from python and it was easy to get the middle digit of an integer, for example, from 897 I want the 9:
>>> num = 897
>>> num2 = int(str(num)[1])
>>> num2
9
But how i can do this on C? It's so difficult to convert into string...
Getting a single digit as an int
can be done mathematically:
int num = 897;
int dig1 = (num / 1 ) % 10;
int dig2 = (num / 10 ) % 10;
int dig3 = (num / 100 ) % 10;
Division by one on the first line is only for illustration of the concept: you divide by n-th power of ten, starting with 100 = 1.
You can try the modulus operator (%).
In your case
num = 897
lastDigit = num%10; // Which returns 7
lastDigit/= 10;
secondLastDigit = lastDigit%10; //Which returns 9
Do this using a while loop for as long as you want. EG.
while(num>0)
{
digit = num%10;
num/=10;
}
The closest approximation in C to the given Python fragment, and its str
operator, is sprintf
/snprintf
:
int num = 897;
char numstr[30];
sprintf(numstr, "%d", num);
char num2 = numstr[1];
int num2n = num2 - '0';
printf("%d\n", num2n);
To guard against buffer overflow, it's safer to get in the habit of using snprintf
rather than sprintf
:
snprintf(numstr, sizeof(numstr), "%d", num);
Instead of sprintf
and %d
, some systems provide an itoa()
function (the opposite of atoi
) for converting integers to strings, but it's not standard. For more information about converting numbers to strings, see Converting int to string in C.
This is "harder" in C than it is in Python for a couple of reasons. Constructing strings from numbers typically involves calls to snprintf
, which is both more flexible and more of a nuisance than just calling str()
. You typically have to worry about how big the destination array (here numstr
) needs to be; this difficulty stems from C's lack of a first-class string type. And C has no convenience method for converting back and forth between digit characters and their values, so C programmers get used to adding and subtracting the constant '0'
(or, if they like to make more work for themselves, 48).
(And the other part of the difficulty stems, I guess, from practicality. C was originally designed for writing operating systems and text editors and system utilities and things. How often do you need the middle digit of a number, anyway?)