清理scanf缓冲区

时间:2017-05-21 20:37:17

标签: c++ scanf

我正在尝试以下列格式阅读输入

XgYsKsC XgYsKsC

其中X,Y,K是双精度值,C是char。

我正在使用以下代码

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;

它在第一次迭代时工作正常,但在第二次迭代时,它使用错误的值执行cout 2次。

所以,我在两个scanf

之后添加了这两行代码
cout << L1g << " " << L1m << " " << L1s << " " << L1c << endl;
cout << L2g << " " << L2m << " " << L2s << " " << L2c << endl;

使用以下输入:

23g27m07sS 47g27m06sW
23g31m25sS 47g08m39sW

我有以下输出:

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

我已经尝试了几种方法来修复它,但没有一种方法可行。我错过了什么?

1 个答案:

答案 0 :(得分:0)

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

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 */
}

在你的情况下,将2组输入绑定到一个......可能更容易。

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卡住,它可能会在输入流中留下意外的字符,从而混淆了后续的读取尝试。

通过读取整行,可以将断开连接限制为单行。通过读取一个scanf中的所有行,它是匹配与否。