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.

+3
c string strtok token


source to share


No one has answered this question yet

Check out similar questions:

721
How would you count the occurrences of a string (actually char) within a string?
6
Strtok () problem: If tokens are delimited, why is the last token between delimiter and null "\ 0"?
2
C tokenizing using strtok prints unexpected values ​​and prevents my strtol validation
1
Token lifetime is returned from strtok
0
Line prints after borders
0
strtok return string?
0
strtok () adds some character to my string
0
Putting an array of 2D symbols into a structure, not sure where to start
0
Storing the final token of a string using strtok ()?
-1
Allocate array dynamically based on content using strtok, strlen, malloc and fgets. C program



All Articles
Loading...
X
Show
Funny
Dev
Pics