有两种不同的方法可以解决您的问题:
-
如果字符串长度是固定的,您可以指定%s 读取的最大字符数并使用此代码:
char str1[3], str2[3];
if (scanf("%2s|%2s", str1, str2) == 2) {
/* read 2 characters into str1, a pipe and 1 or 2 characters into str2 */
}
-
如果字符串长度是可变的,例如在某些行的座位数不同的飞机上,您可以使用扫描集 %[OX] 并指定要读取的字符数,以防止意外输入时潜在的缓冲区溢出。这是一个例子:
char str1[5], str2[5]; // handle up to 4 seats on each side */
if (scanf("%4[OX]|%4[OX]", str1, str2) == 2) {
/* read a group of 1 to 4 `X` or `O` into str1 and str2, separated by | */
}
您可以添加另一个转换以进一步验证该行是否具有预期的格式。这是一个例子:
#include <stdio.h>
int main(void) {
char buf[128];
int i, n, c;
char left[3], right[3];
if (fgets(buf, sizeof buf, stdin) == NULL) {
fprintf(stderr, "invalid format, empty file\n");
return 1;
}
if (sscanf(buf, "%d %c", &n, &c) != 1 || n < 0) {
fprintf(stderr, "invalid format, expected positive number: %s\n", buf);
return 1;
}
for (i = 0; i < n; i++) {
if (fgets(buf, sizeof buf, stdin) == NULL) {
fprintf(stderr, "missing %d lines\n", n - i);
return 1;
}
if (sscanf(buf, "%2[XO]|%2[XO] %c", left, right, &c) != 2) {
fprintf(stderr, "invalid format: %s\n", buf);
return 1;
} else {
printf("row %d: %s | %s\n", i + 1 + (i >= 12), left, right);
}
}
return 0;
}