Froobyflake Froobyflake - 1 year ago 100
C Question

Sum the digits of a phone number using scanf

I want my code to prompt the user to input a phone number of form 1(xxx)-xxx-xxxx and then sum the digits of the number. However I do not know what is wrong with my code. See below

printf("Enter a phone number in 1(xxx)-xxx-xxxx format: \n");
scanf(" %*c%*c%d %d %d %*c%*c%d %d %d %*c%d %d %d %d", &i, &j, &k, &l, &m, &n, &o, &p, &q, &r);

sum = (i + j + k + l + m + n + o + p + q + r);
realsum = sum + 1;

printf("The sum of the digits = %d \n\n", realsum)


Can anyone help? It seems to be assigning the first part of the number (xxx) entirely to i, and j is zero. How do I get it to assign each digit to each variable one by one?

Answer Source

You did account for the non-integer characters that the user enters, but integers are read as a whole, so 123 is not read as1 then 2 then 3 but rather as 123.

scanf(" %*c%*c%d %*c%*c%d %*c%d ", &i, &j, &k);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download