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?
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)
As already pointed out, every string in C should be null-terminated (else - how could printf
know where the string ends?)
You need to search the array for new-lines, presumably using strchr.
Try this:
char * first_newline = strchr(str, '\n');
if (first_newline)
*first_newline = '\0'
It will terminate the string at the first instance of a newline.
EDIT: Take a look at this ;)
How to print only certain parts of a string?
You'll just have to print 'strings lenths - 1' characters
It seems that you read data in array str
using standard function fgets
(or some other method) that includes in the string also the new line character '\n'
that coresponds to Enter key.
You shoud remove this character. This can be done the following way
size_t n = strlen( str );
if ( n && str[n-1] == '\n' ) str[n-1] = '\0';
来源:https://stackoverflow.com/questions/30260986/how-to-print-a-string-using-printf-without-it-printing-the-trailing-newline