Simon Over
Simon Over

Reputation: 21

scanf("%s %s", buffer) not returning second string?

char buffer[128]
ret = scanf("%s %s", buffer);

This only allows me to print the first string fed into console. How can I scan two strings?

Upvotes: 2

Views: 5678

Answers (5)

Anand Padole
Anand Padole

Reputation: 1

#include<stdio.h>

int main(){
int i = 0,j =0;
char last_name[10]={0};
printf("Enter sentence:");
i=scanf("%*s %s", last_name);
j=printf("String: %s",last_name)-8;
/* Printf returns number of characters printed.(String: )is adiitionally 
printed having total 8 characters.So 8 is subtracted here.*/
printf("\nString Accepted: %d\nNumber of character in string: %d",i,j);
return 0;
}

Upvotes: 0

Matthew Murdoch
Matthew Murdoch

Reputation: 31463

if you want to reuse buffer you need two calls to scanf, one for each string.

ret = scanf("%s", buffer);
/* Check that ret == 1 (one item read) and use contents of buffer */

ret = scanf("%s", buffer);
/* Check that ret == 1 (one item read) and use contents of buffer */

If you want to use two buffers then you can combine this into a single call to scanf:

ret = scanf("%s%s", buffer1, buffer2);
/* Check that ret == 2 (two items read) and use contents of the buffers */

Note that reading strings like this is inherently insecure as there is nothing preventing a long string input from the console overflowing a buffer. See http://en.wikipedia.org/wiki/Scanf#Security.

To fix this you should specify the maximum length of the strings to be read in (minus the terminating null character). Using your example of buffers of 128 chars:

ret = scanf("%127s%127s", buffer1, buffer2);
/* Check that ret == 2 (two items read) and use contents of the buffers */

Upvotes: 3

pmg
pmg

Reputation: 108978

You need to choose two different locations for the first and second strings.

char buffer1[100], buffer2[100];
if (scanf("%99s%99s", buffer1, buffer2) != 2) /* deal with error */;

Upvotes: 1

Sandeep Pathak
Sandeep Pathak

Reputation: 10747

If you know the number of words you want to read, you can read it as :

char buffer1[128], buffer2[128];
ret = scanf("%s %s", buffer1, buffer2);

Alternatively you can use fgets() function to get multiword strings .

  fgets(buffer, 128 , stdin);

See Example

Upvotes: 0

check123
check123

Reputation: 2009

char buffer[128], buffer2[128];
ret = scanf("%s %s", buffer, buffer2);

Upvotes: 5

Related Questions