How to check data on strlen when last token \ n counts as strlen
I am reading a file to input and tokenize a string to get various components to populate a structure.
Every line I read, or every line I tokenise is separated by a newline character, so this is the line that I tokenize. I am passing tokens to an array and checking the data from the array.
I test each token for string length and sometimes a different validation.
The problem is that the last marker of the last line of the file has no data, but a new line is entered, it passes the validation check for strlen, but still it is an empty string.
I tried to check the number of tokens, but if a separator exists, the token was counted.
I'm not sure how to check this.
I tried strcmp for '\ n' and '\ 0'
char tokens[MAX_ARRAY][MAX_TOKEN_LEN];
char *str;
char *token;
const char *s = "|";
int count =0;
token = strtok(str, s);
while(token != NULL)
{
strcpy(tokens[count], token);
/*add token to struct*/
token = strtok(NULL, s);
count++;
}
/*check that there are correct number of tokens/fields*/
if(count!=4)
{
return false;
}
if(strlen(tokens[3])<1||strlen(tokens[3])>MAX_DESC_LEN)
{
return false;
}
/*to test if this is not the last string in the file and only
a newline is entered, as it will pass the MIN_DESC_LEN test,
but the ending \n will be changed to \0
I have also tested for if(strcmp(tokens[3],"\n")==0) */
if(strcmp(tokens[3],"\0")==0)
{
return false;
}
Interestingly, any line that is not the last line, an empty token at the end will give a failed validation.
edit: I've also tried:
if(strlen(tokens[3])==1&&tokens[3][strlen(tokens[3])-1]=='\0')
{
return false;
}
and
if(strlen(tokens[3])==1&&tokens[3][strlen(tokens[3])-1]=='\n')
{
return false;
}
I have asked the minimum length just for this question.
source to share
No one has answered this question yet
Check out similar questions: