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

扶醉桌前 提交于 2019-12-04 19:37:48

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.

Guillaume Munsch

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';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!