【问题标题】:Print vector of coordinates obtained from a text file in a specific format in C++在 C++ 中以特定格式打印从文本文件中获得的坐标矢量
【发布时间】:2013-09-02 16:19:11
【问题描述】:

以下是我正在处理的代码 -

#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iterator>

using namespace std;

struct coord {
long x,y;
};

int main()
{
ifstream nos("numbers.txt");
vector< long > values;
double val;
while ( nos >> val )
{
    values.push_back(val);
}

copy(values.begin(), values.end(), ostream_iterator<double>(cout, "\n" ));
return 0;

}

我知道这里不需要初始 struct,但我希望使用它。我希望我的输入文本文件是这样的 -

1,2
2,3
4,5

然后我使用我的程序,将这些数字输入到一个向量中,并以相同的格式打印出该向量

谁能告诉我这样做的正确方法是什么?

我已参考following 获取代码,但我需要阅读并以上述格式打印出来,我不确定最好的方法是什么。

为了更清楚 - 我正在尝试实现凸包算法。我试图同时在编程方面做得更好,因此有了这样的跳跃。

【问题讨论】:

  • 所以你想读一个int,忽略一个逗号,然后一个int,每行一对?这是您要处理的确切格式吗?
  • 在一部分你说print out that vector in the same format,然后你说I need to read and print out in a specific format。是哪一个?

标签: c++ vector convex-hull


【解决方案1】:

对于这么简单的事情可能有点矫枉过正,但我​​会分别重载 ostream 和 istream 输出和输入运算符。

编辑:我猜由于结构具有默认的公共变量,因此您不需要朋友类,但我会保留它,因为这是重载 >

的常见做法
struct coord {
    long x,y;

    friend class ostream;
    friend class istream;
};

istream& operator>>( istream& is, coord& c )
{
     char comma;
     return is >> c.x >> comma >> c.y;
}

ostream& operator<<( ostream& os, const coord& c )
{
     char comma = ',';
     return os << c.x << comma << c.y;
}

int main()
{
    ifstream nos("numbers.txt");
    vector< coord > values;

    coord val;
    while ( nos >> val )
        values.push_back(val);

    for each( value : values )
        cout << value << endl;

    return 0;
}

【讨论】:

    【解决方案2】:

    问题:为什么要混合double long?我假设您想在整个代码中使用long。做你想做的最简单的方法是添加一个虚拟变量,读取数字之间的,

    int main()
    {
    ifstream nos("numbers.txt");
    vector< long > values;
    long val1, val2;
    char dummy;
    while ( nos >> val1 >> dummy >> val2)
    {
        values.push_back(val1);
        values.push_back(val2);
    }
    
    copy(values.begin(), values.end(), ostream_iterator<long>(cout, "\n" ));
    }
    

    另外,您定义了一个名为coord 的结构,但您没有在代码中使用它。如果您想使用它,可以使用以下代码:

    std::ostream& operator<<(std::ostream& os, const coord& c)
    {
        os << c.x << " " << c.y;
        return os;
    }
    
    int main()
    {
    ifstream nos("numbers.txt");
    vector< coord > values;
    coord c;
    char dummy;
    while ( nos >> c.x >> dummy >> c.y )
    {
        values.push_back(c);
    }
    
    copy(values.begin(), values.end(), ostream_iterator<coord>(cout, "\n" ));
    }
    

    此外,在 C++11 中,您可以将代码更改为:

    long x, y;
    char dummy;
    while ( nos >> x >> dummy >> y )
    {
        values.emplace_back(coord{x, y});
    }
    

    或者您也可以查看 std::pair&lt;long, long&gt; 以将您的坐标放入其中。

    【讨论】:

    • 我最初只是尝试使用结构。后来我遇到了我在帖子中提到的那个链接,并添加了那段代码。感谢您为我澄清这一点!
    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2016-03-16
    • 2017-08-05
    相关资源
    最近更新 更多