How can I read a digit as single digit within a number?
int main() {
long long int num1;
printf("enter number: ");
scanf("%lld", &num1);
for example if user input is 123456789, how can I use 4 as a single digit?
How can I read a digit as single digit within a number?
int main() {
long long int num1;
printf("enter number: ");
scanf("%lld", &num1);
for example if user input is 123456789, how can I use 4 as a single digit?
Because the scanf()
call in the question uses the %lld
specifier, which interprets input in base ten, we can assume you want digits in base ten. Assuming the number is positive:
100000
. This gives 1234. If you want to retrieve a variable digit, you can use repeated division by 10 to move the correct digit into the one's place, as shown in Ashiquzzaman's answer. If you instead want digits from the left, start by counting digits in the number: divide it by 10 until the quotient is zero.%
to extract the remainder from division by 10. This gives 4.If the number is negative, division in C rounds toward zero. This means -123456789
will produce -1234
after the first step and -4
after the second.
You can take input as long long int
then extract the digit as follow:
#include <stdio.h>
#include<math.h>
int getDigit(long long number, int idx)
{
number = abs(number);
while(idx--)
number/=10;
return number%10;
}
int main()
{
long long int num1;
int indexOfDigit = 4;
printf("enter number: ");
scanf("%lld", &num1);
printf("%d\n", getDigit(num1, indexOfDigit));
}
Sample input: 123456789
Sample Output: 5
Read it as a sequence of chars (basically, as if it were a string), using %c in scanf in a loop until EOF is read
int main()
{
int digit;
printf("enter number: ");
digit = getchar();
while (digit != EOF)
{
/* Process digit */
digit = getchar();
}
}
You can store the input as a char* and access to the digits with char[3] for the fourth digit?