简体   繁体   English

scanf(“%s%s”,缓冲区)没有返回第二个字符串?

[英]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? 如何扫描两个字符串?

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

if you want to reuse buffer you need two calls to scanf , one for each string. 如果要重用buffer ,则需要两次调用scanf ,每个字符串一次。

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 : 如果你想使用两个缓冲区,那么你可以将它组合成一个对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 . 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: 使用128个字符的缓冲区示例:

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

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 */;

#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;
}

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()函数来获取多字符串。

  fgets(buffer, 128 , stdin);

See Example 见例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM