-1

I am having problems when it comes to printing/displaying a char *string

This is my string

    char *messageForServer = ("netsvr type0 dobrien %s- %s",inet_ntoa(clientAddr.sin_addr),port);

and when I go to print it like

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

it will only print the port part of the string. Will be greatfull for any help as it is bugging me for hours and cant seem to find an answer

Derek O Brien
  • 173
  • 1
  • 3
  • 14

3 Answers3

1

You should do it like this:

char messageForServer[100];
sprintf(messageForServer, "netsvr type0 dobrien %s- %s", "something", "8080");
printf("%s\n", messageForServer);

UPD: which prints the following

netsvr type0 dobrien something- 8080

The reason why your code doesn't work is - well, the way you try to get a formatted string has nothing to do with string formatting in C. See Creating C formatted strings (not printing them) for more information.

Community
  • 1
  • 1
oopcode
  • 1,912
  • 16
  • 26
0

In C, a char * can be created and initialized by assigning a string literal:

char *string = {"some text here"};  

It will not understand the initializer you tried,

("netsvr type0 dobrien %s- %s",inet_ntoa(clientAddr.sin_addr),port);  

for at least two reasons: 1) because it contains more than a literal string, and 2), the ( ) enclosures are syntactically wrong (use { } instead).

If you want to create a string comprised of more than simple text (i.e. a string literal), say for example a string comprised of two strings, an integer and a float, you can do it this way:

char string[NUM_CHAR];

sprintf(string, "%s %d %s %f", "Example of string with ", 4, "elements, including the float:", 3.15); 
ryyker
  • 22,849
  • 3
  • 43
  • 87
0

I think what you're trying to do here is provide a reusable function to print a "message for server" at various points in your code. You might consider doing exactly that: define a messageForServer() function as opposed to your attempt at a pre-formatted string.

void messageForServer(char *msg, char *code)
{
    printf("netsvr type0 dobrien %s - %s\n", msg, code);
}

Simple. Clean. Reusable.

alpartis
  • 1,086
  • 14
  • 29