Search code examples
carraysstringcharfgets

How do I rid newline "\n" from my array of strings after populating it with fgets()?


The array I'm working with is:

char arr[91][12];

So I populate my array from a file using a for loop like so:

for(i = 0; fgets(arr[i], 12, inFile); i++){}

When I want print anything from that array, it's automatically escaping to the next line.

to test that array:

for(i = 0; fgets(arr[i], 12, inFile); i++){
    printf("%s", arr[i]);
}

//one
//two
//three etc.

//want it to be 'one two three etc.'

I'm trying to use strpbrk() to find \n for each string in the array and change it to \0 like this:

for(i = 0; fgets(arr[i], 12, inFile); i++){
if(strpbrk(arr[i], "\n") != NULL ){
    arr[i][strpbrk(arr[i], "\n")] = '\0';
    }
printf("%s", arr[i]);
}

but this gives me errors. Is there a better way to do what I'm trying to do?


Solution

  • It's actually much simpler than you seem to think. If the newline is at the end (as it is when reading with fgets) just change the last character to the string terminator:

    arr[i][strlen(arr[i]) - 1] = '\0';
    

    The -1 is because arrays (like strings can be considered to be) starts their indexing on zero and goes to length - 1.


    To make sure you really have a newline, you can use e.g. strpbrk like you do (but of course not in the way you do it as explained in other answers). But I think it would be a better idea to use strrchr. First because it's simpler (only searching for character not string), second because it starts searching from the end:

    char *newlineptr = strrchr(arr[i], '\n');
    if (newlineptr != NULL)
        *newlineptr = '\0';
    

    Or the fastest way of all:

    size_t length = strlen(arr[i]);
    if (arr[i][length - 1] == '\n')
        arr[i][length - 1] = '\0';