How to print a string using printf without it printing the trailing newline

Tiagofer picture Tiagofer · May 15, 2015 · Viewed 20.8k times · Source

I'm trying to print some strings using printf() but they are null terminated having trailing newline and that messes with the formating:

printf("The string \"%s\" was written onto the file \"%s\"", str, fname);

Say the string contains "The Racing car." and the file name is "RandomText1.txt" This prints:

The string "The Racing car.
" was written onto the file "RandomText1.txt
"

However I want it to print in just one line:

The string "The Racing car." was written onto the file "RandomText1.txt"

I know I can modify the strings to get rid of the null terminator newline but I'd like a way, if possible, to achieve this output without modifying the strings.

Is it possible?

Answer

Sourav Ghosh picture Sourav Ghosh · May 15, 2015

This has nothing to do with the null terminator. a string must be null-terminated.

You're facing issues with the trailing newline (\n) here. you have to strip off that newline before passing the string to printf().

Easiest way [requires modification of str]: You can do this with strcspn(). Pseudo code:

str[strcspn(str,"\n")] = 0;

if possible, to achieve this output without modifying the strings.

Yes, possible, too. In that case, you need to use the length modifier with printf() to limit the length of the array to be printed, something like,

printf("%15s", str);  //counting the ending `.` in str as shown

but IMHO, this is not the best way, as, the length of the string has to be known and fixed, otherwise, it won't work.

A little flexible case,

printf("%.*s", n, str);

where, n has to be supplied and it needs to hold the length of the string to be printed, (without the newline)