I am making code to analyze some input data and write it to a file in special formatting. I delete a new line from each token like this:
token[strlen(token)-2] ='\0'
This is -2 because the last element is \0 . It works a lot. Nevertheless, the last element of the input data does NOT have a new line, so the use of only this ends with the removal of the second-last character from the last set of input data.
original input: 0.38 after running it through the removal: 0.3
The obvious solution is to check for a new line before deleting. I'm doing it:
if(token[strlen(token)-2] =='\n') token[strlen(token)-2] ='\0';
However, after adding the if clause, the new line is no longer deleted! What am I doing wrong? Snippit from all 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); } }