-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_input.c
85 lines (64 loc) · 1.62 KB
/
test_input.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdbool.h> // For booleans in C
#include "Definitions.h"
/**
Read string
*/
string read_string(const char* prompt)
{
string input;
printf("%s", prompt);
// The line below is attributable to Andrew Cain, Swinburne University of Technology
scanf("%255[^\n]%*c", input.str); // scan input for 255 characters that are not new lines
return input;
}
/**
Read integer
*/
int read_integer(const char* prompt)
{
string line;
char temp;
int input;
line = read_string(prompt);
while(sscanf(line.str, "%i %c", &input, &temp) != 1)
{
printf("Please enter a whole number. \n");
line = read_string(prompt);
}
return input;
}
/**
Read integer range
*/
int read_integer_range(const char* prompt, const int lower_int, const int upper_int)
{
int input;
string error_message;
input = read_integer(prompt);
while(input < lower_int || input > upper_int)
{
/*
Sprintf facilitates concatenation between strings and integers in C. This
function is used here to enter the lower and upper bounds of the range in
between which input is sought from the user
*/
sprintf(error_message.str, "Please enter a number between %i and %i", lower_int, upper_int);
printf("%s\n", error_message.str);
input = read_integer(prompt);
}
return input;
}
int read_integer_min_restricted(const char* prompt, const int lower_int)
{
int input;
string error_message;
input = read_integer(prompt);
while(input < lower_int)
{
sprintf(error_message.str, "Please enter a number greater than %i", lower_int - 1);
printf("%s\n", error_message.str);
input = read_integer(prompt);
}
return input;
}