I'm trying to write a simple C function for command line input that checks whether the user's input was too long. I've left the debug prints in to show what happens.
bool read_line(char str[])
{
char c = '\0';
int max_chars = sizeof(str) / sizeof(char);
printf("%d\n", max_chars);
int i = 0;
while (true) {
c = getchar();
if (c == '\n' || c == EOF) {
break;
}
printf("The value of c is %c\n", c);
i++;
printf("The value of i is %d\n", i);
if (i > max_chars) {
return false;
}
printf("Inserting character %c\n", c);
str[i] = c;
printf("str[i] is %c\n", str[i]);
}
return true;
}
The testing code is:
char str[] = {[0 ... SIZE - 1] = 0};
bool length_valid = read_line(str);
if (!length_valid) {
printf("Input too long\n");
return 1;
}
puts(str);
return 0;
Here is the output from running the program; I entered the line "forth".
8
forth
The value of c is f
The value of i is 1
Inserting character f
str[i] is f
The value of c is o
The value of i is 2
Inserting character o
str[i] is o
The value of c is r
The value of i is 3
Inserting character r
str[i] is r
The value of c is t
The value of i is 4
Inserting character t
str[i] is t
The value of c is h
The value of i is 5
Inserting character h
str[i] is h
8
forth
The value of c is f
The value of i is 1
Inserting character f
str[i] is f
The value of c is o
The value of i is 2
Inserting character o
str[i] is o
The value of c is r
The value of i is 3
Inserting character r
str[i] is r
The value of c is t
The value of i is 4
Inserting character t
str[i] is t
The value of c is h
The value of i is 5
Inserting character h
str[i] is h
<Empty line>
The string was clearly shown to be filled with characters moments before, yet somehow in the intervening time it has become null.