如果您对可能从用户那里收到的字符串数以及每个字符串中的字符数设置了上限,并且所有字符串都在一行中输入,则可以通过以下步骤执行此操作:
- 用
fgets()阅读全文,
- 使用
sscanf() 转换说明符的最大数量的格式字符串解析带有sscanf() 的行。
这是一个最多 10 个字符串的示例,每个字符串最多 32 个字符:
char buf[400];
char s[10][32 + 1];
int n = 0;
if (fgets(buf, sizeof buf, sdtin)) {
n = sscanf("%32s%32s%32s%32s%32s%32s%32s%32s%32s%32s",
s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9]));
}
// `n` contains the number of strings
// s[0], s[1]... contain the strings
如果单个字符串的最大长度不固定,或者如果字符串可以在连续的行中输入,则如果不知道最大数量,则需要使用简单的循环进行迭代:
char buf[200];
char **s = NULL;
int n;
while (scanf("%199s", buf) == 1) {
char **s1 = realloc(s, (n + 1) * sizeof(*s));
if (s1 == NULL || (s1[n] = strdup(buf)) == NULL) {
printf("allocation error");
exit(1);
}
s = s1;
n++;
}
// `n` contains the number of strings
// s[0], s[1]... contain pointers to the strings
除了错误处理之外,此循环与上面的硬编码示例相当,但它仍然具有每个字符串的最大长度。除非您可以使用 scanf() 扩展来自动分配字符串(在 GNU 系统上为 %as),否则处理任意长度的任意数量的字符串会更加复杂。