'Inserting spaces between digits in C
How would I go about taking a number like 123456 and having it print as 1 2 3 4 5 6?
Solution 1:[1]
The simplest way of doing this (though not the fastest) would probably be to first sprintf the number to a string buffer, and then loop through the buffer printf-ing one character and one space at a time.
There's no built-in way of doing this within the standard printf formatting.
Solution 2:[2]
A common method would be to extract each digit, and then print that digit. I won't give you the code, but it's the implemented version of:
int d; // your number
/* While `d` is not zero */
/* Modulus `d` with 10 to extract the last digit */
/* Print it, with your space */
/* Divide by 10 to remove the last digit */
/* Repeat */
This will be backwards. I'll leave it as an exercise to you to fix that. (Hint: In the loop, put the result into an array of characters, and when you're finished start at the last index of the array and print backwards.)
Solution 3:[3]
char buffer[50];
int myNum = 123456;
int n;
int i;
n = snprintf(buffer, sizeof buffer, "%d", myNum);
for (i = 0; i < n; i++)
{
putchar(buffer[i]);
putchar(' ');
}
putchar('\n');
Solution 4:[4]
int number = 123456;
char strNumber[64];
strNumber[0] = '\0';
sprintf_s(strNumber, "%d", number);
int i = 0;
while(strNumber[i] != '\0')
printf("%c ", strNumber[i++]);
Solution 5:[5]
This only works for unsigned integers:
#include <stdio.h>
#include <math.h>
void print_number(unsigned int number) {
int n = number, c = 0, p;
while (n > 0) {
n /= 10;
c++;
}
for (n = c - 1; n >= 0; n--) {
p = pow(10, n);
printf("%d ", number / p);
number -= number / p * p;
}
printf("\n");
}
int main(int argc, char *argv[]) {
print_number(1);
print_number(12);
print_number(123);
print_number(1234);
print_number(12345);
print_number(1234567);
print_number(12345678);
print_number(123456789);
return 0;
}
Solution 6:[6]
#include <stdio.h>
int main ()
{
int a, b, c, d, e;
printf("Write a number of four figures\n");
scanf("%d", &a);
printf("Your number is:\n");
b = (a - (a % 1000)) / 1000;
c = ((a - (a % 100)) / 100) - b * 10;
d = ((a - (a % 10)) / 10) - b * 100 - c * 10;
e = (a - b * 1000 - c * 100 - d * 10);
printf("%d\t%d\t", b, c);
printf("%d\t", d);
printf("%d", e);
return 0;
}
Solution 7:[7]
#include <stdio.h>
#include <conio.h>
int main ()
{
int n, a, b, c, d, e;
printf("Enter integer number from 0 to 32, 767: ");
scanf("%d", &n);
printf("\n");
a= n/10000%10;
b= n/1000%10;
c= n/100%10;
d= n/10%10;
e= n%10;
printf("%d %d %d %d %d\n", a, b, c, d, e);
RESULTS/OUPUT:
Enter integer number from 0 to 32,767: 12345
1 2 3 4 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | dreamlax |
| Solution 4 | ratnaveer |
| Solution 5 | Leonardo Herrera |
| Solution 6 | bunbun |
| Solution 7 | Suraj Rao |
