Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you add a newline to the end of a string in C?

I am using the editline library to get user input and hand that input to a scanner. The scanner requires any valid input to end with a newline character to unambiguously indicate the end of the last token. However, the input returned by the readline function doesn’t end with a newline character.

What is the best way to now add a (newline) character to the end of the string buffer which is
not large enough?

The first and the most simple solution I came up with was this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

char* input = readline("> ");
if (!input) { ... }
size_t len = strlen(input) + 2;  // Additional space for newline and null-terminator.
input = (char*) realloc (input, len);
input[len - 2] = '\n';  // Overwrites original '\0'
input[len - 1] = '\0';

Since this is part of a REPL performance isn’t too important here so this should work fine. Still, I think this might end up copying lots of data if input cannot simply be extended in memory by realloc.
Is there a more clever way to do this or is this one of the problems where we simply have to do some copying?

>Solution :

If there’s no space for one more character, there’s no space; nothing you can do but copy to a larger memory area.

Implementation-wise, you could replace your explicit setting of characters with strcat, but as you already know the length of the string, that would be less perfarmant (potentially; I bet modern compilers can optimize the hell out of that).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading