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

问题描述 投票:2回答:5
char buffer[128]
ret = scanf("%s %s", buffer);

这只允许我打印送入控制台的第一个字符串。如何扫描两个字符串?

c scanf
5个回答
5
投票
char buffer[128], buffer2[128];
ret = scanf("%s %s", buffer, buffer2);

3
投票

如果你想重用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 */

如果你想使用两个缓冲区,那么你可以将它组合成一个scanf调用:

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

请注意,读取这样的字符串本质上是不安全的,因为没有什么能阻止来自控制台的长字符串输入溢出缓冲区。见http://en.wikipedia.org/wiki/Scanf#Security

要解决此问题,您应指定要读入的字符串的最大长度(减去终止空字符)。使用128个字符的缓冲区示例:

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

1
投票

您需要为第一个和第二个字符串选择两个不同的位置。

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

0
投票

如果您知道要阅读的单词数,可以将其读作:

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

或者,您可以使用fgets()函数来获取多字符串。

  fgets(buffer, 128 , stdin);

See Example


0
投票

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.