如何在C ++中分割x和y坐标

时间:2015-11-04 04:47:27

标签: c++

对于我的CS入门课程,我应该阅读类似

的内容
N = 4
(0.5,1) (0.6,1.5) (0.7,2) (0.8,2.5)

并打印

X := [0.5, 0.6, 0.7, 0.8]
Y := [1, 1.5, 2, 2.5]

到目前为止我的代码看起来像

#include <iostream>
using namespace std;

int main()
{
  int size;
  char c;
  double point;

  cin >> c >> c >> size;

  int N = size*2;

  double *A = new double[N];
  for(int i = 0; i < N; ++i)
    cin >> c >> A[i];
  cin >> c;

  cout << A << endl;
  return 0;
}

这只是读取现在的要点......但我无法弄清楚双括号的情况。而其余的问题。任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:2)

您可以通过c ++中的向量进行尝试。您可以从中学习vectorpair

现在好了,正是你想要的:

#include <iostream>
#include <cstdio>
#include <vector>

using namespace std;

int main ()
{
    vector < pair <double, double> > v;

    int N = 4;
    for (int i=0; i<N; i++)
    {
        double x,y;
        scanf("(%lf,%lf)", &x, &y);
        v.push_back(pair <double, double>(x,y));
        getchar();
    }

    cout<< "X := ["<< v[0].first;
    for (int i=1; i<N; i++)
        cout<<" ,"<<v[i].first;
    cout<< "]"<<endl;

    cout<< "Y := ["<< v[0].second;
    for (int i=1; i<N; i++)
        cout<<" ,"<<v[i].second;
    cout<< "]"<<endl;

    return 0;
}

输入:

(0.5,1) (0.6,1.5) (0.7,2) (0.8,2.5)

输出:

X := [0.5, 0.6, 0.7, 0.8]
Y := [1, 1.5, 2, 2.5]

答案 1 :(得分:0)

首先,我认为使用vector和pair c ++ stl的所有建议都是正确的。但是,考虑到mid_code刚开始他的编程之旅,我认为使用数组是一种很好的练习方式。我想你可以使用两个双数组来存储关于点的信息。

#include <iostream>
using namespace std;
#include <iostream>
using namespace std;

int main()
{
    int n;
    char c;

    cin >> c >> c >> n;
    // store x, y coordinates in two separated arrays.
    double *x = new double[n];
    double *y = new double[n];
    for (int i = 0; i < n; i++) {
        // Read x, y coordiantes and ignore the parenthesis and comma.
        cin >> c >> x[i] >> c >> y[i] >> c;
    }

    cout << "X := [";
    for (int i = 0; i < n; i++) {
        cout << x[i];
        // Here worth beginner's attention.
        if (i < n - 1) {
            cout << ", ";
        }
    }
    cout << "]" << endl;

    cout << "Y := [";
    for (int i = 0; i < n; i++) {
        cout << y[i];
        if (i < n - 1) {
            cout << ", ";
        }
    }
    cout << "]" << endl;

    return 0;
}