简体   繁体   中英

Multiple scanf from a single input

I am trying to prompt the user for a number, and then extract the number they entered and also sum the digits of the number they entered. They can only enter the number once. My code is below:

    printf("\nPART 2: EXPRESSIONS SUM\n\n");
    printf("Enter 5-digit integer: ");
    scanf("\n%1d%1d%1d%1d%1d", &dig_one, &dig_two, &dig_three, &dig_four, &dig_five);
    scanf("\n%d", &five_dig_int)

However after the first scanf completes, the program gets hung on the second scanf waiting for more input. Is there a way to "re scan" so to speak on the initial input so the user does not have to enter the number again? Thanks! ;

Use a string & atoi()

Example:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    char str[6];
    printf("\nPART 2: EXPRESSIONS SUM\n\n");
    printf("Enter 5-digit integer: ");
    scanf("\n%s, &str);
    int fivedigit = atoi(str);
    int sum = 0;
    for(int i = 0; i < 5; i++)
    {
        int tempadd = (int) str[i];
        sum += tempadd;
    }
    //Do stuff with both values



}

It's not hard to sum the base 10 digits of any integer with a bit of arithmetic:

#include <stdio.h>

int main(void) {
  int val;
  printf("Enter a number: ");
  if (scanf("%d", &val) != 1) return 1;
  int sum = 0;
  for (int x = val; x; x /= 10) sum += x % 10;
  printf("Value = %d. Digit sum = %d\n", val, sum);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM