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

时间:2011-11-15 10:24:59

标签: c scanf

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

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

5 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分: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 */

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

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

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

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

  fgets(buffer, 128 , stdin);

See Example

答案 4 :(得分: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;
}