Froobyflake
Froobyflake

Reputation: 43

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?

Upvotes: 0

Views: 710

Answers (2)

Hypnic Jerk
Hypnic Jerk

Reputation: 1192

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);

Upvotes: 1

user3386109
user3386109

Reputation: 34829

The problem is that %d keeps reading until it finds a character that can't be part of a decimal number. So if the user enters 1(123)-456-7890 then the first %d will set i to 123.

The solution is to use %1d. That tells scanf to read a one-digit decimal number.

btw: you should verify that the return value from scanf is correct. In this example, the correct return value is 10. Any other number indicates that the user did not enter a valid phone number.

Upvotes: 4

Related Questions