2 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
最好使用char buf[big_enough * 2]; fgets(buf, sizeof buf, stdin)讀取行然后解析它(最好使用sscanf(buf, " { [ %lf ...和)sscanf(buf, " { %lf ...。
但是,如果代碼必須保留scanf():
OP的第一個(gè)scanf(" { [ %lf ...消費(fèi)了'{'預(yù)期的第二個(gè)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貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
您應(yīng)該使用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 關(guān)注
- 748 瀏覽
添加回答
舉報(bào)