我有以下输入:
((1828,299),(2729,2553),(2797,2929),(2200,1383),(2894,876))
和以下结构:
struct x{
int a;
int b;
}
如何使用 scanf() 读取输入以创建我的结构数组?
我试过了
scanf("%[^, ()],%d", &arr);
if (i % 2 == 0){
arr[i].x = scanf("%d");
}else
arr[i].y = scanf("%d");
但是当我试图打印出这些值时,我得到了一些奇怪的字符
最佳答案
错误使用scanf()
scanf("%[^, ()],%d", ...)
期望扫描并形成一个字符串 ("%[^, () ]"
) 和一个int
("%d"
)。代码只提供了一个地方来保存int
。代码没有检查
scanf()
的返回值,因此如果没有发现任何扫描问题则进行编码。
当数据是行时,推荐使用fgets()
,然后解析。可以使用 strtok() strtol() sscanf()
。每个都有各种优点/缺点。示例:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXN (5)
// maximum size needed to print and `int`
#define INTSIZE (sizeof (int )* CHAR_BIT / 3 + 3)
// Expect buffer size needed
#define EXPECTEDSIZE (1+(2*INTSIZE + 4) + 3)
void fooo() {
int i;
struct x {
int a;
int b;
} xx[MAXN];
char buf[EXPECTEDSIZE * 2]; // I favor 2x size buffers
while (fgets(buf, sizeof buf, stdin)) {
char *p = buf;
if (*p++ != '(') {
exit(EXIT_FAILURE);
}
for (i = 0; i < MAXN; i++) {
int n; // use %n to locate scan completion
int cnt = sscanf(p, " (%d ,%d ) %n", &xx[i].a, &xx[i].b, &n);
fprintf(stderr, "cnt = %d '%s'\n", cnt, p);
if (cnt != 2) {
exit(EXIT_FAILURE);
}
p += n;
if (p[0] != ',') {
if (p[0] == ')') {
i++;
break; // Successfully reached the end
}
exit(EXIT_FAILURE);
}
p++;
}
int j;
for (j=0; j< i; j++) {
printf("%d (%d ,%d )\n", j, xx[j].a, xx[j].b);
}
}
}
关于c - 使用 scanf() 从括号中读取逗号分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29583743/