2 回答
TA贡献1831条经验 获得超4个赞
最好使用char buf[big_enough * 2]; fgets(buf, sizeof buf, stdin)读取行然后解析它(最好使用sscanf(buf, " { [ %lf ...和)sscanf(buf, " { %lf ...。
但是,如果代码必须保留scanf():
OP的第一个scanf(" { [ %lf ...消费了'{'预期的第二个scanf( " { %lf ...
代替:
if(scanf(" { [ %lf ; %lf ] , [ %lf ; %lf ] , [ %lf ; %lf ] }%c",
&A[0], &A[1], &B[0], &B[1], &C[0], &C[1], &s) != 7 && s != '\n') {
s = ' ';
// no {
// v
if(scanf(" %lf , %lf , %lf }%c", &a, &b, &c, &s) != 4 && s != '\n') {
printf("error\n");
return 1;
}
}
首选fgets()方式:
// Form a reasonable, yet generous buffer
#define I (50 /* rough estimate of characters use to read a double, adjust as needed */)
// { [ 1 ; 1 ] , [ 3 ; 1 ] , [ 2 ; 2 ] }\n\0
#define LINE_SIZE_EXPECTED (4 + I+3+I +7 +I+3+I +7 +I+3+I+6)
char buf[LINE_SIZE_EXPECTED * 2]; // Lets us use 2x for extra spaces, leading zeros, etc.
if (fgets(buf, sizeof buf, stdin)) {
// Consider using "%n" to detect a complete scan and check for no trailing junk
int n = 0;
sscanf(buf, " { [ %lf ; %lf ] , [ %lf ; %lf ] , [ %lf ; %lf ] } %n",
&A[0], &A[1], &B[0], &B[1], &C[0], &C[1], &n);
if (n && buf[n] == '\0') {
// successful scan
} else {
n = 0;
sscanf(" { %lf , %lf , %lf } %n", &a, &b, &c, &n);
if (n && buf[n] == '\0') {
// successful scan
} else
// both scans failed
}
}
}
TA贡献1887条经验 获得超5个赞
您应该使用sscanf。
以下code可能有效:
#include <stdio.h>
int main() {
double a, b, c, A[2], B[2], C[2];
char *s = NULL;
size_t n = 0;
getline(&s, &n, stdin);
if(sscanf(s, " { [ %lf ; %lf ] , [ %lf ; %lf ] , [ %lf ; %lf ] }", &A[0], &A[1], &B[0], &B[1], &C[0], &C[1]) != 6
&& sscanf(s, " { %lf , %lf , %lf }", &a, &b, &c) != 3) {
printf("error\n");
return 1;
}
// rest of the code...
printf("success\n");
return 0;
}
- 2 回答
- 0 关注
- 719 浏览
添加回答
举报