LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   A question about strings... (https://www.linuxquestions.org/questions/programming-9/a-question-about-strings-878495/)

trist007 05-03-2011 03:01 AM

A question about strings...
 
This question is about C. Say I have a string 'test'. By looking at the chars we have { 't', 'e', 's', 't', '\0' }

Say I wanted to add a ': ' after it so that it becomes
{ 't', 'e', 's', 't', ':', ' ' }
I use the following code to implement this.
Code:

char str[16] = "test";
int len;
len = strlen(str);
len = len +2;
str[len - 2] = ':';
str[len - 1] = ' ';
str[len] = '\0';

So that should do it because the string is null-terminated. Yet when I run a
Code:

printf("%s", str);
Nothing gets printed. However, if I do the following instead
Code:

printf("%s\n", str);
It prints just fine. Why is that? I could always just do
Code:

write(STDOUT_FILENO, str, sizeof(str));
which works fine but I'd like to understand why printf without the newline prints nothing.

dwhitney67 05-03-2011 03:31 AM

Quote:

Originally Posted by trist007 (Post 4344764)
Yet when I run a
Code:

printf("%s", str);
Nothing gets printed.

Usage of the \n in the printf() function will force the standard-out stream to be flushed. Since you haven't a newline above, the string is not printed. Practice with either of these:
Code:

printf("%s\n", str);
or with:
Code:

printf("%s", str);
printf("\n");

Btw, you could have saved yourself the trouble when augmenting the string using strncat().
Code:

strncat(str, ": ", sizeof(str));
Typically, however, one does not declare a string larger than necessary. Thus memory allocation comes into play. Read up the usage of malloc() and realloc(). You would need to declare a char pointer versus a char array when using these functions.

trist007 05-03-2011 03:52 AM

Thanks that explains it.


All times are GMT -5. The time now is 09:54 PM.