/*C program to get a string with letters and numbers from the
user then find the sum of all the numbers in the string */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main()
{
char ch;
int j;
char str1[9];
int sum = 0;
printf("\n\n Please enter a string of letters and numbers: ");
gets(str1);
printf("\n\n");
printf(" Printing the numbers in the string\n");
printf("\n\n Numbers found in string ");
printf("\n\n");
for (j = 0; j < strlen(str1); j++) {
if(isdigit(str1[j]))
printf(" %c ", str1[j] );
}
printf("\n\n Calculating the sum of the numbers in the string\n");
for (int j = 0; j < strlen(str1); j++){
if(isdigit(sum += j))
printf(" %d ",str1[j]);
}
scanf("%c%c", &ch, &ch);
return 0;
}
views:
69answers:
1
+1
A:
This application of isdigit
doesn't look right:
if(isdigit(sum += j))
...
Compare that to how it is used in the previous for loop, where you are just searching for digits. The if
condition should look the same here, and then sum
should be incremented in the if
's body.
sth
2010-07-06 19:26:05
and should be incremented by the value at index **j** not **J** itself
Gollum
2010-07-06 19:29:48