I am making a code to parse some input data and write it to a file in a special formatting. I am removing a newline from each string token as so:
token[strlen(token)-2] ='\0'
It is -2
because the last element is \0
. This much works. However, the final element of the input data does NOT have a newline, so using just that ends up removing the second-to-last character from the last input set.
original input: 0.38
after running it through the removal: 0.3
The obvious solution is to check if the newline is there before removing. I do this:
if(token[strlen(token)-2] =='\n') token[strlen(token)-2] ='\0';
However, after adding the if clause, the newline is no longer removed! What am i doing wrong? Snippit from the whole code:
while((token = strsep(&line, ",")) != NULL){
if(x++ == 1){
fwrite(" <item>\n", 11, 1, fw);
fwrite(" <name>", 14, 1, fw);
fwrite(token, strlen(token), 1, fw);
fwrite("</name>\n", 8, 1, fw);
}
else if(isdigit(token[0])) {
if(token[strlen(token)-2] =='\n') token[strlen(token)-2] ='\0';
fwrite(" <SPC>", 13, 1, fw);
fwrite(token, strlen(token), 1, fw);
fwrite("</SPC>\n", 7, 1, fw);
fwrite(" </item>\n", 12, 1, fw);
}
}