2017-05-21 58 views
0

我想在下面的格式读取输入清洁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 

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

+3

总是检查'scanf'的返回值,对于初学者。 – hyde

+3

如果您使用C++编程,为什么要使用'scanf'?如果你想处理输入错误,那么我建议你[读整行](http://en.cppreference.com/w/cpp/string/basic_string/getline),把它放到[输入字符串流] (http://en.cppreference.com/w/cpp/io/basic_istringstream),然后使用普通的“输入”操作符'>>'尝试解析该行。如果你坚持使用'scanf',那么请创建一个[最小化,完整和可验证示例](http://stackoverflow.com/help/mcve)并向我们展示。 –

+0

Scanf比cin更快,它确实计入编程竞赛 –

回答

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中的所有行,它可以匹配或不匹配。