Numberstring

I want to have an output which is when I enter
ab123 cd456 the output would be 6 15 . . and if ever I Din't enter spaces like this hasd121433463 the output would be 27.

devc++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 #include<stdio.h>
main(){

int num, num2, count=0;
char arrayNum[10]= {"0123456789"}, x[50];

   printf("\nEnter the code: ");
   scanf("%s",x);

for(num=0;num<strlen(x);num++){
for(num2=0;num2<=9;num2++){          
if(arrayNum[num2]==x[num]){
count+=arrayNum[num2]-48;
break;
             
}
}
}
printf("%d",count);

getch();
}
arrayNum should be initialied like this: '0','1',2','3','4','5','6','7','8','9' since is it not a string but char.

Aceix.
The arrayNum is not needed at all. There is predicate isdigit.

The magic - 48 assumes that the numeric value of '0' is 48. One could as well use - '0'.

One could read one character at a time. It is safer than to assume that input has at most 49 characters.

There is predicate isspace that could be used to spot end of word.
some inputs:

12jksd45

output:12


12 24 or 12fjfkdfk 24
output: 3 6

12 24
output:3 6


12sdfsdf 242 sdfsdfsd43

output : 3 8 7


if you enter letter it should be ignored . (check!)


MY ONLY PROBLEM IS ! the spaces should be read. if I enter spaces between the numbers the summutation will be stop AND start another summutation again

PLEASE I NEED IT.


Last edited on
At start, you don't have a word and the sum is 0.

Read one character at a time. If you get a digit, then you have a word and the sum increases.

If you get a whitespace and you already have a word,
then you show the sum, reset sum to 0 and you no longer have a word.

When you have run out of characters, if you still have a word, then you show the final sum.
Last edited on
Topic archived. No new replies allowed.