-
Notifications
You must be signed in to change notification settings - Fork 3
/
getinput.c
50 lines (44 loc) · 1.27 KB
/
getinput.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
#include "getinput.h"
void getDynamicInput(char **userInputBuffer)
{
ssize_t charsRead = 0;
size_t len = 0;
charsRead = getline(userInputBuffer, &len, stdin);
size_t pos = strcspn(*userInputBuffer, "\n");
*(*userInputBuffer + pos) = 0;
}
int getInput(char *userInputBuffer, size_t length)
{
int rc;
rc = getLine("Enter string: ", userInputBuffer, length);
if (rc == NO_INPUT) {
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", userInputBuffer);
return 1;
}
return 0;
}
int getLine(char *prompt, char *buff, size_t maxInputLength)
{
int ch, extra;
// Get line with buffer overrun protection.
if (prompt != NULL) {
printf ("%s", prompt);
fflush (stdout);
}
if (fgets (buff, maxInputLength, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. Flush to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}