C++ 清洁扫描缓冲区

C++ 清洁扫描缓冲区,c++,scanf,C++,Scanf,我正在尝试读取以下格式的输入 XgYsKsC XgYsKsC 其中X,Y,K是双值,C是字符 我正在使用以下代码 scanf("%lf%*c%lf%*c%lf%*c", &L1g, &L1m, &L1s); scanf(" %c", &L1c); scanf("%lf%*c%lf%*c%lf%*c", &L2g, &L2m, &L2s); scanf(" %c", &L2c); double lat = (L1g * 3600

我正在尝试读取以下格式的输入

XgYsKsC XgYsKsC
其中X,Y,K是双值,C是字符

我正在使用以下代码

scanf("%lf%*c%lf%*c%lf%*c", &L1g, &L1m, &L1s);
scanf(" %c", &L1c);

scanf("%lf%*c%lf%*c%lf%*c", &L2g, &L2m, &L2s);
scanf(" %c", &L2c);

double lat = (L1g * 3600 + L1m * 60 + L1s) / 3600.0;
double len = (L2g * 3600 + L2m * 60 + L2s) / 3600.0;

cout << setprecision(2) << fixed << lat << " " << len << endl;
我得到了以下输出:

23 27 7 S
47 27 6 W
23.45 47.45 // all fine until here
23.00 27.00 7.00 g // It should be printed 23 31 25 S
31.00 25.00 6.00 S // It should be printed 47 8 39 W
23.45 31.45 // Wrong Answer
23.00 27.00 7.00 g // And it repeats without reading inputs
8.00 39.00 6.00 W
23.45 8.65

我试过几种方法来解决这个问题,但没有一种有效。我遗漏了什么?

我对这种问题的标准模式是

while( fgets( buffer, sizeof(buffer), stdin ) != NULL ) { /* for each line */
     if( sscanf( buffer, "%lf%*c%lf%*c%lf%*c", &L1g, &L1m, &L1s) == 3 ) {
        /* handle input which met first criteria.
     } /* else - try other formats */
}
在您的情况下,将两组输入绑定到一个中可能更容易

while( fgets( buffer, sizeof(buffer), stdin ) != NULL ) { /* for each line */
     if( sscanf( buffer, "%lf%*c%lf%*c%lf%*c %lf%*c%lf%*c%lf%*c", &L1g, &L1m, &L1s, &L2g, &L2m, &L2s)) == 6 ) {
        /* handle input which met first criteria.
     } /* else - try other formats */
}
通过分隔行,可以限制数据和解析状态之间的断开连接。如果[s]scanf被卡住,它可能会在输入流中留下意外字符,从而混淆后续的读取尝试


通过读取整条线路,将断开连接限制为一条线路。通过读取一个SCAN中的所有行,它要么匹配要么不匹配。初学者/< P>总是检查“代码> SCANF的返回值,如果是C++编程,为什么使用代码> SCAFF < /代码>?如果您想处理输入中的错误,我建议您将其放入,然后使用正常的“输入”操作符
>
尝试解析该行。如果您坚持使用
scanf
,请创建一个并向我们展示。scanf比cin更快,它确实依赖于编程竞赛在第一次输入时,scanf返回3,1,3,1,这是正确的。在第二次输入时,它返回0,1,2,1,它应该是3,1,3,1。在我看来,如果你试图进行竞争性编程,却不知道如何使用像
scanf
这样的函数并进行错误检查,你将不会从中学到任何东西。首先学习如何编写好程序,以及如何制作好的、有良好文档记录的和有效的程序。然后你可以去研究竞争性编程。不要为了学习如何编程而这样做,那么你所要学的就是做(糟糕的)竞争性编程(糟糕的),而不是别的。
while( fgets( buffer, sizeof(buffer), stdin ) != NULL ) { /* for each line */
     if( sscanf( buffer, "%lf%*c%lf%*c%lf%*c", &L1g, &L1m, &L1s) == 3 ) {
        /* handle input which met first criteria.
     } /* else - try other formats */
}
while( fgets( buffer, sizeof(buffer), stdin ) != NULL ) { /* for each line */
     if( sscanf( buffer, "%lf%*c%lf%*c%lf%*c %lf%*c%lf%*c%lf%*c", &L1g, &L1m, &L1s, &L2g, &L2m, &L2s)) == 6 ) {
        /* handle input which met first criteria.
     } /* else - try other formats */
}