简体   繁体   中英

scanf each digit of integer AND store the whole number in C

Example input: 12345

As you can see I can store each digit "1" "2" "3" "4" "5" through scanf but how do I store the whole number "12345"? Can it happen within the same scanf line?

#include <stdio.h>
#include <math.h>


int main(){

    int wholeNumber = 0;
    int i1,i2,i3,i4,i5 = 0;

    printf("\nPlease enter a five digit integer value.\n");
    scanf("%1d%1d%1d%1d%1d",&i,&i2,&i3,&i4,&i5); //scanning each digit but 
                                                 //how do I store the whole #?
    return 0;
}

I will try to answer your first question. You can simply multiply the entered numbers by multiples of 10. Lets show it with calculation:

5*1 + 4*10 + 3*100 + 2*1000 + 1*10000 = 12345

So, here is the code for a manual use:

...
scanf("%1d%1d%1d%1d%1d",&i,&i2,&i3,&i4,&i5);
i*=10000;
i2*=1000;
i3*=100;
i4*=10;
i5*=1;
...

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