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
我已經嘗試了幾種方法來解決這個問題,但都沒有成功。我錯過了什麼?
總是檢查'scanf'的返回值,對於初學者。 – hyde
如果您使用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)並向我們展示。 –
Scanf比cin更快,它確實計入編程競賽 –