I need to output the sum of the numbers that are inside of a sentence. For example :
I need to read all the sentences include the space to do this, but my loop with getchar
doesn't work. Can help me to find the problem?
int main() {
int i = 0;
int somma = 0;
char s[MAX];
printf("inserisci la stringa : ");
scanf("%s",s);
while((s[i] = getchar()) != '\n'){
i++;
if(s[i]>'0' && s[i]<'9'){
somma+= (int)s[i]-(int)'0';
}
}
printf("la somma è = %d", somma);
}
I don’t have to use getchar
. I would prefer to use fgets
because I know that fgets
can read the entire line including the space.
There are two ways to solve your problem.
To read entire string, you can use scanf
as you are using it. It will store entire string in array (s
in your case) and then you can parse this array and peform operations as you are doing. Here limitation would be length of string. You can accept string of the MAX
size only as your array is of that much size. If you are okay with this, then your code is correct. All you need to do is remove that getChar()
from while
.
Alternatively, you can read one character at a time from user and immediately perform operations on that character. In that case, you don't need to declare array. One character variable is sufficient and you can go on accepting data from user. In this case, discard the scanf()
and in your while()
, accept getChar()
output in one character and perform your operation.
P.S. There's one small bug in your while() which will give you incorrect result in few cases.