strtok will not remove the newline (or any of the given separators) if there aren't any non-separator characters in the string. However, if there are no non-separator characters in the string, strtok will return NULL, so you can use that to tell if the line is empty. You may as well include other whitespace characters in the separator list, and you can even use the returned pointer to skip any initial whitespace.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
while (1) {
puts("Enter the ID:");
if (fgets(str, sizeof str, stdin) == NULL)
break;
char *p = NULL;
if ((p = strtok(str, " \t\n")) == NULL)
continue;
printf("size of string %d\n", (int)strlen(p));
}
return 0;
}
Try entering some spaces, 12345, and some more spaces.
Alternatively, you could use strcspn like so:
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
while (1) {
puts("Enter the ID:");
if (fgets(str, sizeof str, stdin) == NULL)
break;
str[strcspn(str, "\n")] = '\0';
printf("size of string %d\n", (int)strlen(str));
}
return 0;
}
Or, if you're really interested in the string length, then you may as well do it in the straightforward way:
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
while (1) {
puts("Enter the ID:");
if (fgets(str, sizeof str, stdin) == NULL)
break;
size_t len = strlen(str);
if (str[len-1] == '\n')
str[--len] = '\0';
printf("size of string %d\n", (int)len);
}
return 0;
}
If you aren't really interested in the string length, the the strtok method is excellent since it allows you to skip initial and trailing space, and with a little extension could be used to detect extraneous (presumably erroneous) non-space characters after the first word.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
while (1) {
puts("Enter the ID:");
if (fgets(str, sizeof str, stdin) == NULL)
break;
char *p = NULL;
if ((p = strtok(str, " \t\n")) == NULL)
continue;
if (strtok(NULL, " \t\n") != NULL) {
printf("Extraneous characters in input!\n");
continue;
}
printf("size of string %d\n", (int)strlen(p));
}
return 0;
}
This considers "one two" an error, but " one " is okay (and is interpreted as "one"). (I meant to add a few spaces before and after "one", but the forum reduces them to one space.)