Deleting a new line does not work after trying to verify it

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); } } 
+2
source share
4 answers

Your new line should be in line[strlen(line)-1] , but you can work on Windows, where the new line actually consists of a carriage return followed by a new line. This explains why line[strlen(line)-2]='\0' successfully deletes the end of the line, but the test fails.

+2
source

I think your problem is to use -2 instead of -1 , use this function to remove spaces on the right side of the line:

 #include <ctype.h> /* remove whitespace from the right */ void rtrim(char *s) { char *p; for (p = s + strlen(s) - 1; p >= s && isspace(p[0]); p--); p[1] = 0; } 
+2
source
 size_t len; for(len=strlen(token); len && (token[len-1] == '\r' || token[len-1] == '\n'); len--) { token[len] = 0; } 

or you can use strcspn ():

 size_t len; len = strcspn(token, "\r\n" ); token[len] = 0; 

Or, as a single line:

 token [ token + strcspn(token, "\r\n" )] = 0; 

Note that the first fragment only deletes the trailing '\ r and' \ n; srcspn () fragments remove all of the first "\ r" or "\ n" that they encounter.

+2
source

For flexibility (no character count, no characters) I would do:

 #include <string.h> ... char * rtrim(char * str, const char * del) { if (str) { char * pc; while (pc = strpbrk(str, del)) { *pc = 0; } } return str; } ... char * line; ... /* let line point to some string */ /* to remove any kind of line end, call it like this: */ line = rtrim(line, "\n\r"); 

This solution covers the ends * IX, ms and mac, and also survives, for example:

 #define char wchar_t 
+2
source

Source: https://habr.com/ru/post/1482027/


All Articles