Ayse
Ayse

Reputation: 2754

Reading from a buffer word by word in c

I have a Buffer received as a result of recvfrom(). lets say,

char buffer[12] = "Hello 1";

I want to separate Hello and 1 and store them in different buffers so that one buffer has "Hello" in it and other buffer or an int variable has "1" stored in it.

In other words I want to separate contents of a buffer on the basis of spaces. How can this be done?

I tried:

int number;
char buff[7];
sscanf (buffer,"%s %d",buff,number);

Will this approach work?

Upvotes: 1

Views: 1465

Answers (3)

Manuel Pires
Manuel Pires

Reputation: 637

This approach works but you need to change to change your sscanf to:

sscanf (buffer,"%s %d",buff,&number);

The %d expects an int* and you are sending an int.

Upvotes: 2

Raghuram
Raghuram

Reputation: 3967

If there are only 2 words your idea will work. But there is a small error in your code. Change the sscanf this way

sscanf (buffer,"%s %d",buff,&number);

Upvotes: 3

Kninnug
Kninnug

Reputation: 8053

Looks like you want strtok, it can do exactly that. But make sure your string is NULL-terminated, recv and other socket functions don't do that for you and the standard C string functions do expect NULL-termination.

Upvotes: 1

Related Questions