有一個 (A,B) 形式的 N 個有序對的串列
示例輸入:
(200,500)
(300,100)
(300,100)
(450,150)
(520,480)
我只想從輸入中獲取數字,以便我可以在我的 Point 結構中使用它們,并使用它們來表示坐標平面上的位置。
這是我的代碼:
#include <bits/stdc .h>
#include <iostream>
#include <vector>
#include <map>
#include <fstream>
using namespace std;
struct Punto
{
double x,y;
double distancia;
double zona;
};
int main()
{
int n=4;
Punto arr[n];
int x, y;
for(int i=0; i<n; i ){
cin.ignore(); //(
std::cin >> x;
arr[i].x = x;
std::cout << "Punto " << i << " x " << x << '\n';
cin.ignore(); //,
std::cin >> y;
arr[i].y = y;
std::cout << "Punto " << i << " y " << y << '\n';
cin.ignore(); //)
}
return 0;
}
問題是這僅適用于第一個條目,但不適用于以下條目。
uj5u.com熱心網友回復:
ignore
除了要忽略的字符外,還將丟棄一個新的行分隔符,這意味著在回圈的第二次迭代cin.ignore()
中將忽略一個新的行字符,使開頭(
仍然在流中并導致std::cin >> x
失敗。
更可靠的方法是讀取分隔符并檢查它們的值,這將有助于檢測檔案格式中的錯誤或代碼中的錯誤,并且還有一個額外的好處,即讀取字符將自動跳過空格,包括新行。
boll readDelim(char expected)
{
char ch;
std::cin >> ch;
return ch == expected;
}
int main()
{
const int n=4;
Punto arr[n];
int x, y;
for(int i=0; i<n; i ){
if (!readDelim('(')) break;
std::cin >> x;
arr[i].x = x;
std::cout << "Punto " << i << " x " << x << '\n';
if (!readDelim(',')) break;
std::cin >> y;
arr[i].y = y;
std::cout << "Punto " << i << " y " << y << '\n';
if (!readDelim(')')) break;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368077.html