forked from jhpy1024/CProgrammingLanguageExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise_1-21.c
66 lines (55 loc) · 1.44 KB
/
exercise_1-21.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <stdbool.h>
#define TAB '\t'
#define SPACE ' '
#define NEWLINE '\n'
#define TAB_WIDTH 4
int count_num_spaces(int* current_char)
{
int num_spaces = 1;
while ((*current_char = getchar()) == SPACE)
{
++num_spaces;
}
return num_spaces;
}
int main()
{
int current_char = EOF;
int char_position = 0;
while ((current_char = getchar()) != EOF)
{
if (current_char == SPACE)
{
int num_spaces = count_num_spaces(¤t_char);
while (num_spaces >= TAB_WIDTH)
{
num_spaces -= TAB_WIDTH;
putchar(TAB);
char_position += TAB_WIDTH;
}
while (num_spaces > 0)
{
--num_spaces;
putchar(SPACE);
++char_position;
}
}
/*
* We don't use an else if statement here because when counting the number
* of spaces above, we change current_char. If we used an else if statement and current_char
* had been changed to a newline, the code to handle that newline would not be executed.
*/
if (current_char == NEWLINE)
{
char_position = 0;
putchar(NEWLINE);
}
if (current_char != NEWLINE && current_char != SPACE)
{
putchar(current_char);
++char_position;
}
}
return 0;
}