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