Help with string processing in C
In the program, to find out if a given number is an Armstrong number , I saved the no (3 digits) input as a string as follows.
char input[10];
scanf("%s",&input);
Now I have to calculate the cube of each digit using the pow math.h method as follows.
int a;
a = pow(input[0],3);
By coding this way I was unable to get the correct result. If I type the value "a" it shows some irrelevant answer. My doubt is how to convert from string value to integer value?
Armstrong numbers are numbers that represent the armstron property at any given base, not just base 10.
int isArmstrong(int n, int b)
{
int sum = 0;
int n2 = n;
int nDigits = 0;
while(n2 != 0)
{
nDigits++;
n2 /= b;
}
n2 = n;
for(int i = 0; i < nDigits; i+++)
{
sum += pow(n2 % b, nDigits);
n2 /= b;
}
return sum == n;
}
source to share
On the other hand, you may need to replace the power with a more general one like power = strlen (input)
so the code should look like this.
char input[10];
int power, sum = 0;
scanf("%s", input);
power = strlen(input);
sum += pow(input[0] - '0', power);
/* you need to compare in here */
source to share
Doh, I could spend too much time in C because I think most of the answers here will miss the end goal ... Undo advice and of course of course, but there are still a few problems with scanf.
First, it should be OK for a code / homework dump, but it's dangerous: enter 11 characters and get a buffer overflow.
Second, IIRC, since you need a number, you must use an int variable and get it. Untested code from a rusty mind:
int inputNumber;
scanf("%d", &inputNumber);
You will also need it here because you no longer have a pointer.
C should do the conversion for you and you have safer input.
Another problematic code:
int a = pow(input[0], 3);
You are not doing math with the first digit, but with the Ascii value of the first digit! I.e. 49 by 1, 50 by 2 ...
Since you have a number from my previous correction, divide it by the correct power of 10 to get a digit.
If you prefer the string route, use input[0] - '0'
as a minimum.
source to share
Freehand coding based on @PhiLho's idea for using actual integer input:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a, sum, i;
printf("Enter an Armstrong number, an integer in the range 100..999:\n");
if(scanf("%d", &a) != 1)
return EXIT_FAILURE;
if(a < 100 || a > 999)
return EXIT_FAILURE;
/* Now extract digits, and compute sum of cubes. */
for(sum = i = 0; i < 3; i++)
{
sum += pow(a % 10, 3);
a /= 10;
}
printf("sum is: %d\n", sum);
return EXIT_SUCCESS;
}
source to share