Avoid assumptions
Code subtracts 1 with no explanation. A usual reason to do so here is an assumed '\n'
at the end of str
.
fgets(str, 100, stdin);
int len = strlen(str);
int len2 = len - 1; // Why - 1?
Consider why this is not always correct.
1) User input was long like "000...(98 total zero characters)...000x\n"
. fgets()
would read the first 99 characters into str
and code would identify that as a good string, even though it had a x
in str
.
2) User input was "012"
and then input was closed. fgets()
would read "012"
into str
and code would identify that as a good string, even though it had a 2
in str
.
3) Some hacker is messing with the program and inputs "0z\0\n"
and code would identify that as a good string, even though input had a 'z'
.
4) fgets()
suffered a rare input error. The state of str
in indeterminate. strlen(str)
leads to UB.
To fix 1,2, 4 and partially #3
if (fgets(str, 100, stdin) == NULL) {
printf("End of file or input error\n");
return 0;
}
int len = strlen(str);
if (len > 0 && str[len-1] == '\n') str[--len] = '\0';
int len2 = len;
Code passes the empty line
I'd expect an input of "\n"
to warrant a "Not Valid...\n"
Goal not cleanly met
Given the task of "Is a string a bit string", code should have a function like
bool is_bit_string(const char *s);
Instead OP's code answered "Is a line of input a bit string".
In C:
A string is a contiguous sequence of characters terminated by and including the first null character.
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined.
'a'
, 'b'
, 'c'
, '\0'
is a string.
'a'
, 'b'
, 'c'
, '\n'
is a line.
Separate core function
The input/output should not be part of "Is a string a bit string". Perhaps:
#include <stdbool.h>
bool is_bit_string(const char *s) {
if (*s == '\0') {
return false;
}
while (*s >= '0' && *s <= '1') {
s++;
}
return *s == '\0';
}
Test code
Move testing of "Is a string a bit string" away from is_bit_string()
definition. perhaps even in separate .c files.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define TEST_SZ 256
bool is_bit_string(const char *s);
int main(void) {
char str[TEST_SZ];
if (fgets(str, sizeof str, stdin) == NULL) {
fprintf(stderr, "End of file or input error\n");
return EXIT_FAILURE;
}
// Lop off potential \n
str[strcspn(str, "\n")] = '\0';
if (is_bit_string(str)) {
printf("Valid!\n");
} else {
printf("Not Valid...\n");
}
return EXIT_SUCESS;
}
len
i.o.len2
, asstr[len] == '\0'
, the functionstrlen
giving size - 1. \$\endgroup\$