"Wrapping" a C char array by putting in '\n' every x characters -- Issue with strcat

StackOverflow https://stackoverflow.com/questions/19850999

  •  29-07-2022
  •  | 
  •  

Pregunta

I have a snippet of C code:

I want to add a new line character at certain intervals. The problem is, when I add it in the if block, on the next iteration, strcat takes it away, then concats s on, and then puts the \n at the end.

I can think of any other way to do this so strcat does not remove the \n that I want to add.

Any ideas?

¿Fue útil?

Solución

hmm... if curPos points to the the next available position in the array, than I would do this. curPos + 1 points after the current '\0' termination of ans, since arrays in C are indexed starting at 0.

   if (i % 8 == 0 && i != 0)
   {
      ans[curPos++] = '\n';
      ans[curPos] = '\0'; /* always null terminate a string after any extension */      
   }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top