C:我怎么能这样做,所以scanf()输入有两种格式之一?

我需要做这个程序,它需要两个三角形并比较它们。

基本上一切都很好,除了用户输入初始数据的部分。 我的主要问题是其中一个条件是用户可以输入三角形的三边长度或三个顶点的X,Y坐标。


我需要它像以下任何一种一样工作:
此输入表示用户使用的边长:

{ 5 , 5 , 5 } 

此输入表示用户使用顶点的X,Y坐标:

 { [ 1 ; 1 ] , [ 3 ; 1 ] , [ 2 ; 2 ] } 

这是我的代码我是如何尝试解决它的,但出于某种原因,如果用户输入使用顶点的第一个条件,检查它是否不是边长,会搞砸一切。

 #include  int main() { double a, b, c, A[2], B[2], C[2]; char s; 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 = ' '; if(scanf(" { %lf , %lf , %lf }%c", &a, &b, &c, &s) != 4 && s != '\n') { printf("error\n"); return 1; } } // rest of the code... printf("success\n"); return 0; } 

如果我交换这两个条件而不是它切换它只有当用户输入使用顶点时…

有可能让它以某种方式简单地工作吗?

使用char buf[big_enough * 2]; fgets(buf, sizeof buf, stdin) char buf[big_enough * 2]; fgets(buf, sizeof buf, stdin)读取该然后解析它,也许用sscanf(buf, " { [ %lf ...sscanf(buf, " { %lf ...


然而,如果代码必须与scanf()保持一致:

OP的第一个scanf(" { [ %lf ...消耗第二个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 } } } 

你应该使用sscanf

以下code可以工作:

 #include  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; }