char buffer[128]
ret = scanf("%s %s", buffer);这只允许我打印输入到控制台的第一个字符串。如何扫描两个字符串?
发布于 2011-11-15 18:29:29
char buffer[128], buffer2[128];
ret = scanf("%s %s", buffer, buffer2);发布于 2011-11-15 18:28:33
如果希望重用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 */发布于 2011-11-15 18:30:34
您需要为第一个和第二个字符串选择两个不同的位置。
char buffer1[100], buffer2[100];
if (scanf("%99s%99s", buffer1, buffer2) != 2) /* deal with error */;https://stackoverflow.com/questions/8134814
复制相似问题