清洁扫描缓冲液

Cleaning scanf buffer

本文关键字:缓冲 扫描 清洁      更新时间:2023-10-16

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

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;

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

所以,我在两次扫描之后添加了这 2 行代码

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

我已经尝试了几种方法来解决这个问题,但没有一种奏效。我错过了什么?

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

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

通过读取整行,这会将断开连接限制为一行。 通过在一个扫描中读取所有一行,它要么匹配,要么不匹配。