C ++ не может заполнить данные

0

Я пытаюсь заполнить мои векторы значениями x и y. но он, похоже, не добавляет, а просто отменяет первое.

main.cpp

#include <iostream> 
#include "Point.h"

using namespace std;
int x,y;
Point point;
string options;
void someMethods();
int main()
{   
    cout << "Please Enter x-Cordinate"<< endl;
    cin >> x;
    cout << "Please Enter y-Cordinate" << endl;
    cin >> y;
    cout << "Enter cords again? yes/no"<< endl;
    cin >> options;
    while (options == "yes") {

        cout << "Please Enter x-Cordinate"<< endl;
        cin >> x;
        cout << "Please Enter y-Cordinate" << endl;
        cin >> y;
        cout << "Enter cords again? yes/no"<< endl;
        cin >> options;
    }


    if(options == "no") {
        Point Point(x,y);
        Point.someMethods();
       // break;
    }
}

Point.h

#ifndef Point_Point_h
#define Point_Point_h
#include <vector>

class Point {
private:
      int x,y;

public : 

      Point() {
       x = 0;
       y = 0;
      } //default consrructor


      Point(int x,int y);
      int getX();
      int getY();
      void setX(int x);
      void setY(int y);
      std::vector<Point> storeData;
      void someMethods();

};    

#endif

Point.cpp

#include <iostream>
#include "Point.h"
using namespace std;


Point::Point(int x,int y) {
setX(x);
setY(y);

}  

int Point::getX() {
  return x;
}
int Point::getY() {
  return y;
}

void Point::setX(int x) {
this->x = x;
}

void Point::setY(int y) {
this->y = y;
}


void Point::someMethods() {
x = getX();
y = getY();

Point Point(x,y);
storeData.push_back(Point);

   for (int i=0; i<storeData.size(); i++) {
    cout << "X "<< storeData[i].getX() <<"Y " << storeData[i].getY() << endl;
   }
// do some methods here after getting the x and y cords;
}  

как я могу сделать это таким образом, что, например, (я введу x и y 3 раза, скажем, 1,1 2,2 3,3)

то он будет выводить

X: 1,Y: 1
X: 2,Y: 2
X: 3,Y: 3
Теги:

3 ответа

2
int main()
{
    // don't need global variables, just define local ones here
    int x,y;
    Point point;
    string options;

    // You shouldn't store the vector of Points in the Point class itself.
    // It doesn't have anything to do with a Point. classes should generally
    // only contain relevant information (ex. Point contains only x and y coords).
    vector<Point> pointsVector;

    // do-while will do the contents of the loop at least once
    // it will stop when the while condition is no longer met
    do
    {
        cout << "Please Enter x-Cordinate"<< endl;
        cin >> x;
        cout << "Please Enter y-Cordinate" << endl;
        cin >> y;

        pointsVector.push_back(Point(x, y));

        cout << "Enter cords again? yes/no"<< endl;
        cin >> options;
    } while (options == "yes")

    // don't really need to check if options is "no"
    // if you have exited the do/while loop above, the assumption is that you don't 
    // want to enter more coordinates.
    doSomethingWithTheVectorOfPoints(pointsVector);

    return 0;
}

В функции doSomethingWithTheVectorOfPoints вы можете поместить код для вывода координат X и Y. (Вы также можете просто прокрутить вектор в основной функции напрямую.)

Кроме того, вы можете добавить функцию-член в свой класс Point, называемый ToString или Print, чтобы выполнить эту работу за вас.

Редактировать: я на самом деле не собирал это, это просто для того, чтобы дать вам представление о том, как вы можете переписать свой код.

  • 0
    Спасибо за совет
0

Вы должны иметь:

  • Нет глобальных переменных
  • Точечный класс, поддерживающий ввод (вывод) потока,
  • Сохраненные данные из класса точек (почему это должно быть плохое решение?)
  • Поток ввода с проверкой.

Пример:

#include <iostream>
#include <stdexcept>
#include <sstream>
#include <vector>

struct Point {
    int x;
    int y;
};

std::istream& operator >> (std::istream& in, Point& point) {
    return in >> point.x >> point.y;
}

typedef std::vector<Point> PointStorage;

int main()
{
    PointStorage point_storage;
    Point point;
    while(true) {
        std::cout << "Please enter X and Y xordinates or 'no' to stop input" << std::endl;
        std::string line;
        if( ! std::getline(std::cin, line))
            throw std::invalid_argument(line);
        else {
            std::istringstream point_input(line);
            // Skip leading white spaces, read a point, skip trailing white apace
            // and ensure no additional character is left.
            if(point_input >> point >> std::ws && point_input.eof()) {
                point_storage.push_back(point);
            }
            else {
                std::string no;
                std::istringstream no_input(line);
                // Skip leading white spaces, read "no", skip trailing white apace
                // and ensure no additional character is left.
                if(no_input >> no >> std::ws && no_input.eof() && no == "no") {
                    break;
                }
                throw std::invalid_argument(line);
            }
        }
    }
    for(PointStorage::const_iterator pos = point_storage.begin();
        pos != point_storage.end();
        ++pos)
    {
        std::cout << pos->x << ", " << pos->y << '\n';
    }
    return 0;
}

Примечание. Исключение броска, вероятно, является плохим решением, но это упрощает пример.

  • 0
    Спасибо за совет
-2

Вы воссоздаете свой объект Point с конечными коордами каждый раз, когда вводите "нет". Вот почему вы держите только последнюю пару.

На несвязанной ноте вы, вероятно, должны значительно упростить код. Нет никаких оснований для того, чтобы объект Point сохранял вектор объектов Point в первую очередь. Вероятно, вы хотите сохранить там историю/последовательность исходных координат и иметь что-то вроде:

Point mypt;

while (options == "yes") {
    mypt.AddCoords(x, y);
    // read more coords/options
}

// do stuff on filled mypt object
  • 0
    Спасибо за совет

Ещё вопросы

Сообщество Overcoder
Наверх
Меню