Search code examples
cnewlinefgetsstrcat

How to add a character "\t" into a string before the newline character "\n"


I am wondering how to take a line of string and add a tab character before the new line character. Right now I'm using fgets to get the line then using

strcat(line_data, "\t");

but that just adds the tab after the newline character


Solution

  • Assuming that line_data has enough memory:

    char* newline = strchr(line_data, '\n');
    newline[0] = '\t';
    newline[1] = '\n';
    newline[2] = '\0';
    

    Of course, if it doesn't, you have to do something like this:

    size_t len = strlen(line_data);
    char* newstr = malloc(len + 2); /* one for '\t', another for '\0' */
    memcpy(newstr, line_data, len);
    newstr[len - 1] = '\t'; /* assuming '\n' is at the very end of the string */
    newstr[len] = '\n';
    newstr[len + 1] = '\0';