My goal in the code is to initialize string with 80 chars, and only when the user typing char that is not \0 , ,\t ,\n . to print "illegal com
It appears that if the user only enters '\0'
, ' '
, '\t'
, '\n'
, no message is printed.
char str[80]="";
is specified to initialize the entire array, yet may not be OP's problem.
Yet it is the footnote1 and comment that may explain OP's unexpected output.
What makes this challenging is that user input may contain null characters, and not just the appended one.
Using getchar()
would be a direct approach.
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (ch != ' ' && ch != '\t' && ch != '\0') {
printf_s("illegal character code: %d\n", ch);
}
}
gets_s();
is trickier to use for the task as it does not return the length read and input may consists of embedded null characters.
To detect embedded null characters, the buffer will not end with a '\n'
and it is hoped (though not specified.1) that the unused portion remain unchanged. So by pre-filling with '\n'
code can distinguish between the appended null characters and one that is read.
int main(void) {
int i;
char str[80];
memset(str, '\n', sizeof str);
if (gets_s(str, sizeof str)) {
int length = sizeof str;
while (length > 0) {
length--;
if (str[length] == '\0') break; // found appended null character
}
for (int i=0; i<length; i++) {
if (str[i] != '\0' && str[i] != '\t' && str[i] != ' ') {
printf("illegal character code: %d\n", str[i]);
}
}
}
}
I prefer the getchar()
approach.
1 The value of the buffer after the appended null character is not specified to be unchanged - yet that is the common case. Hmmmm, but if it was changed, that would explain OP's problem. So another reason to avoid
gets_s();
here.