I want to separate a 5 digit number taken in through scanf()
into three different variables. The first variable should have the first digit, the second should have the second 2 digits, and the third should have the last 2 digits.
I was thinking of something like this:
int num1;
int num2;
int num3;
scanf(%1d%2d%2d, &num1, &num2, &num3);
However, this doesn't work: it assigns the last two digits to every variable.
Is there any way to do this without separating the number after scanning in all 5 digits?
Change this:
scanf(%1d%2d%2d, &num1, &num2, &num3);
to this:
scanf("%1d%2d%2d", &num1, &num2, &num3);
since you forgot to use the double quotes.
See this example:
#include <stdio.h>
int main(void) {
int num1, num2, num3;
scanf("%1d%2d%2d", &num1, &num2, &num3);
printf("%d %d %d\n", num1 ,num2, num3);
return 0;
}
Output:
> 12345
1 23 45
See it for yourself in this Live Demo
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.