-
Notifications
You must be signed in to change notification settings - Fork 124
/
exercise04.c
67 lines (52 loc) · 1.15 KB
/
exercise04.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
67
// C Primer Plus
// Chapter 11 Exercise 4:
// Design and test a function like that described in Programming Exercise 3
// except that it accepts a second parameter specifying the maximum number of
// characters that can be read.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#define SIZE 20
char * getword(char *target, int max);
int main(void)
{
// test getword()
char hello[SIZE] = "Hello, ";
int space = SIZE - strlen(hello) - 1;
puts("What's your name?");
getword(hello + 7, space);
puts(hello);
return 0;
}
char * getword(char *target, int max)
{
// read input into character array target
// stop after first word , EOF or max characters
// discard rest of the line
char ch;
int i = 0;
bool inword = false;
while ((ch = getchar()) != EOF && i < max)
{
if (isspace(ch))
{
if (inword)
break; // word is over, exit while loop
else
{
continue; // skip leading whitespace
}
}
// if ch is not whitespace
if (!inword)
inword = true;
*(target + i) = ch;
i++;
}
// discard rest of the line if any
if (ch != '\n')
while ((ch = getchar()) != '\n')
continue;
return target;
}