Reputation: 21
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
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
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
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
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);
Upvotes: 0
Reputation: 2009
char buffer[128], buffer2[128];
ret = scanf("%s %s", buffer, buffer2);
Upvotes: 5