簡體   English   中英

從只有一行的流中讀取點

[英]Read points from a stream that is only one line

我有一個文件,它首先告訴我我將在下一行閱讀多少點。 因此,例如我的文件如下所示:

7
a,b c,d e,f g,h, i,j k,l m,n

所以我知道 7 之后的下一行是 7 對整數,用逗號分隔,每對用空格分隔。

我想要的是:擁有 7 個 Point 元素的向量。

我有一個名為 Point 的類:

class Point {
public:
    int x;
    int y;
    bool operator==(const Point q){
        return (q.x == this->x && q.y == this->y);
    }
};

因此,當我閱讀此文件時,我想要一個向量 V,其中:

V[0].x = a
V[0].y = b
V[1].x = c
V[1].y = d

等等。

我可以很好地讀取 7,但是如何分別讀取 7 對整數中的每一對? 我需要這個,因為我要將 (a,b) (c,d)... 存儲在一個向量中。

不僅是2分。 文件的第一行告訴我要存儲多少點。

它們不是從標准輸入中讀取的。

它們是從文件中讀取的。

我嘗試使用 sscanf 但我認為這僅適用於您有多行包含此信息並且我不想修改我的格式。

這是我到目前為止:

void process_file(string filename){
    ifstream thracklefile;
    string line;
    int set_size;
    thracklefile.open(filename);

    getline(thracklefile,line); //store set size.
    set_size = stoi(line);

    //Store points in following line
    points.clear();
    points.resize(set_size);
    getline(thracklefile,line); //store the points.
    }

我不想忽略逗號,每個逗號都是我想為每個 Point 存儲的信息的一部分。

我認為評論中的大部分討論都是關於語義的。 建議您“忽略”逗號,但您不能這樣做,因為它們在文件中。 也許更好的術語是“丟棄”。 使用“忽略”一詞是因為有一個 C++ iostream 函數ignore

有很多方法可以處理這個問題。 一種選擇是覆蓋流插入/提取運算符:

class Point {
public:
    int x;
    int y;

    // Don't really need this as members are public, but
    // in case you change that in the future....
    friend istream& operator>>(istream& in, Point& p);
    friend ostream& operator<<(ostream& out, const Point& p);
};

istream& operator>>(istream& in, Point& p)
{
    char separator;
    // Try to read <int><char><int>
    in >> p.x >> separator >> p.y;
    // The stream may be in an error state here. That
    // is ok. Let the caller handle that
    // Also note that we discard (ignore) "separator"
    return in;
}
ostream& operator<<(ostream& out, const Point& p)
{
    out << p.x << ',' << p.y;
    return out;
}

int main() {
    int num_points;
    std::cin >> num_points;
    Point p;
    for (int i = 0; i < num_points; i++) {
        if (!(std::cin >> p)) {
            // There was an error
            std::cout << "File format error!" << std::endl;
            break;
        }
        std::cout << p << std::endl;
    }

    return 0;
}

該示例使用cin但任何流都應該可以工作,包括ifstream

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM