Execution time comparison [duplicate] - c++

This question already has answers here:
How to Calculate Execution Time of a Code Snippet in C++
(18 answers)
Closed 8 years ago.
I have a snowball launcher game codes. There is a arm to launch snowball and the target in the game. I have 2 different block of codes that makes the calculation for releasing angle of the arm with the input of length of the arm and target's x and y coordinates. One of them is:
#include <iostream>
#include <cmath> // math library
#include <windows.h> // system()
using namespace std;
class SnowballMachine{
private:
double L,X,Y, theta; //L for Lenght of the arm, X and Y is the coordinates
const double pi = 3.14159265; //Theta=Release angle
public:
void input() //get inputs for lenght of the arm and coordinates
{
cout<<"Please enter the coordinations of the target(for Target(x,y) enter 40 28)" <<endl;
cin>>X>>Y;
cout<<"Please enter the length of the arm: "<<endl;
cin>>L;
}
double calculate(){ //calculates the release angle with perpendicular slope comparison
if(L*Y <= X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))
{
theta=asin((L*Y + X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y, 2.0)+pow(X, 2.0)));
return theta;
}
else
{
theta=asin((L*Y - X*sqrt(pow(Y, 2.0)+pow(X, 2.0)-pow(L, 2.0)))/(pow(Y,2.0)+pow(X, 2.0)));
return theta;
}
}
void ThetaDisplay() //displays output
{
cout << "The releasing angle is "<<180-(theta*180/pi)<<" degrees"<<endl;
}
};
//const values for options to get input
const int OPEN_GATE=1 ;
const int LOAD_SNOWBALL = 2;
const int ADJUST_ARM=3;
const int RELEASE_ARM=4;
const int QUIT=5;
int menu(); // get a command
void execute(int, SnowballMachine &Dummy); // run a given command
int main()
{
SnowballMachine A; //calling the class
A.input(); //calling the functions
A.calculate();
int choice;
A.ThetaDisplay();
do //select the options
{
choice = menu();
execute(choice, A);
} while (choice != QUIT );*/
return 0;
}
int select;
system("cls");
do
{
cout <<"1....Open the gate\n";
cout <<"2....Load the Snowball\n";
cout <<"3...Adjust the arm\n";
cout <<"4....Release the Snowball\n";
cout<<"5...Quit\n";
cout <<"enter selection: ";
cin >> select;
} while (select!=1 && select!=2 && select!=3 && select!=4 &&select!=5);
return select;
}
void execute(int cmd, SnowballMachine &Dummy)
{
//options switch method
switch (cmd)
{
case OPEN_GATE: cout << "Opening the gate\n";
break;
case LOAD_SNOWBALL: cout << "Loading the snowball\n";
break;
case ADJUST_ARM:cout<<"Adjusting the arm\n";
break;
case RELEASE_ARM:cout<<"Releasing the arm\n";
Dummy.calculate();
Dummy.ThetaDisplay();
break;
case QUIT:cout<<"Quitting!!!";
break;
default:
cout <<" Invalid Entry. Try it again please.";
}
This is the first one. Second one is:
This is the main.cpp
#include <iostream>
#include "Snowball.h"
using namespace std;
int main()
{
Snowball A;
A.Display();
A.ArmLength();
A.Input();
A.SetStartPOS();
for(double i = A.getLength(); i>A.getStartPOS(); i-=A.DELTAX)
{
if (A.Derivative(A, i)*.9999 >= ((A.getY()-A.foo(i))/(A.getX()-i))*1.0001)
{
A.setxPointcirc(i);
break;
}
}
A.AngleDisplay();
return 0;
}
This is the part of main.cpp which is snowball.cpp which calls all the functions:
#include "Snowball.h"
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void Snowball::Input()
{
cout << "Enter the x-postion of the target: ";
cin >> x;
while(x < armlength || x < armlength*-1)
{
cout << endl;
cout << "Please make sure your x is greater than " << armlength << '.' << endl;
cout << "Enter the x-postion of the target. ";
cin >> x;
}
cout << "Enter the y-postion of the target: ";
cin >> y;
while(y < 0 || (y < armlength && x<armlength) )
{
cout << endl;
cout << "Enter the y-postion of the target: ";
cin >> y;
}
this->x =x;
this->y =y;
}
void Snowball::ArmLength()
{
cout << "Enter the Length of the Arm: ";
cin >> armlength;
this->armlength =armlength;
}
void Snowball::Display()
{
cout << "Welcome to the Snowball Launcher. \n\n";
}
double Snowball::foo(double x)
{
double z;
z = sqrt(powf(armlength, 2.0)-powf(x, 2.0));
return z;
}
double Snowball::Derivative(Snowball &foo_dummy, double x)
{
return (foo_dummy.foo(x+DELTAX/2.0) - foo_dummy.foo(x-DELTAX/2))/DELTAX;
}
void Snowball::AngleDisplay()
{
theta = rad2deg(acos(xPointCircle/armlength));
cout << "\nTarget Destroyed.\nAngle Required is: " << theta << " degrees." << setprecision(4) <<endl;
}
void Snowball::SetStartPOS()
{
StartPOS = armlength*-1;
}
void Snowball::setxPointcirc(double i)
{
xPointCircle = i;
}
And here is the getters and setters with declaring the const and variables header:
#ifndef SNOWBALL_H_INCLUDED
#define SNOWBALL_H_INCLUDED
#include <iostream>
#include <cmath>
using namespace std;
class Snowball {
private:
double rad2deg(double h) {return h*(180/pi); };
double x, y, theta, xPointCircle, StartPOS, armlength;
public:
static const double pi = 3.1415926535897;
static const double DELTAX = 0.001;
double foo(double x);
double Derivative(Snowball &foo_dummy, double x);
void Display();
void Input();
double getLength() {return armlength; }
double getStartPOS() {return StartPOS; }
double getY() {return y; }
double getX() {return x; }
void setxPointcirc(double i);
void ArmLength();
void AngleDisplay();
void SetStartPOS();
};
#endif
Here is my question: I get the same results with both 2 different block of codes. I want to
test which execution time is less(which one would be faster?).

Generally the way this is approached is to call the function n number of times (for large n) and calculate the time taken across the calls.
For instance, call it "the first way" 100000 times (getting the time before and time after) then calculate it "the second way" the same number of times (again checking the time before and after). By subtracting the two, you'll get a decent estimate of which is faster/slower.
Note that you need to test it many numbers of times to get an accurate result, not just once!

Related

How to fix logical errors caused by incorrectly calling the functions in C++

The main goal of the program is to ask the user for a shape, dimensions of the said shape, and to calculate its' area. Using the functions is required.
I'm pretty sure the error lies within
int main()
and
void shape_output(...
void area_output(...
functions
#include <iostream>
#include <iomanip>
using namespace std;
void show_menu();
int user_choice();
int calc_area();
void shape_output(int);
void area_output(int);
int main()
{
int area;
int shape;
show_menu();
shape = user_choice();
area = calc_area();
shape_output(shape);
area_output(area);
return 0;
}
void show_menu()
{
cout << "Calculating the area of a shape\n\n"
<< "1. Circle\n"
<< "2. Rectangle\n"
<< "3. Square\n"
<< "4. Quit\n"
<< "Enter the number of your choice: " << endl;
}
int user_choice()
{
int CIRCLE = 1;
int SQUARE = 2;
int RECTANGLE = 3;
int QUIT = 4;
int choice;
cin >> choice;
if(choice < CIRCLE || choice > QUIT)
{
cout << "Please enter a valid menu choice" << endl;
cin >> choice;
}
return choice;
}
int calc_circle()
{
double radius,
area,
Pi = 3.14;
cout << "Enter the radius: ";
cin >> radius;
if(radius < 0)
{
cout << "Invalid, Try again: ";
cin >> radius;
}
area = Pi * radius * radius;
return area;
}
int calc_rectangle()
{
double height,
width,
area;
cout << "Enter the height: ";
cin >> height;
if(height < 0)
{
cout << "Invalid, Try again: ";
cin >> height;
}
area = height * width;
return area;
}
int calc_square()
{
double base,
area;
cout << "Enter the base: ";
cin >> base;
if(base < 0)
{
cout << "Invalid, Try again: ";
cin >> base;
}
area = base * base;
return area;
}
void quit()
{
cout << "Have a good day!\n";
}
int calc_area()
{
const int CIRCLE = 1;
const int SQUARE = 2;
const int RECTANGLE = 3;
const int QUIT = 4;
int choice = user_choice();
switch(choice)
{
case CIRCLE:
calc_circle();
break;
case SQUARE:
calc_square();
break;
case RECTANGLE:
calc_rectangle();
break;
case QUIT:
quit();
break;
default:
quit();
return 0;
break;
}
return choice;
}
void shape_output(int answer_choice)
{
cout << "Shape: " << answer_choice << endl;
}
void area_output(int answer_area)
{
cout << "Area: " << answer_area << endl;
}
I expect the output to be as such:
choose the shape:
number of the shape
specific dimension of a shape:
dimension(s)
shape: chosen shape
area: calculated area
but the output im getting is:
choose the shape:
number of the shape
number of the shape ( I have to put it in twice)
specific dimension of a shape:
dimension(s)
shape: number of the chosen shape, not the actual word
area: number of the chosen shape again.
Basically, I realized that my whole code was garbage, so I wrote it all from the start.
I had a lot of problems with correctly calling the functions and filling in the parameters and arguments, so I looked at some basic tutorials on functions and incoroporated them into my code.
Thanks everyone for the comments.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
//Declaring function prototypes.
int question();
double option(int);
double input_fun();
double calc_circle(double);
double calc_square(double);
double calc_rect(double, double);
void output(double, double);
// main function where all the other functions are called from
int main()
{
int choice; // not related to `int choice` in `double question()`
// Data from question() function will be stored in `int choice`.
double option_case; // Data from `double option()` will be stored here.
choice = question();
option_case = option(choice);
output(choice, option_case);
return 0;
}
// function to prompt the user to choose a shape or quit
int question()
{
int choice;
cout << "Please choose a shape\n"
<< "Press 1 for CIRCLE\n"
<< "Press 2 for SQUARE\n"
<< "Press 3 for RECTANGLE\n"
<< "Press 4 to QUIT\n";
cin >> choice;
while (choice < 1 && choice > 4)
{
cout << "Invalid entry, Try again: \n";
cin >> choice;
}
return choice;
}
// Function to determine user's choice
double option(int choice)
{
double calc_area,
radius,
length,
width;
switch (choice) // Depending on user's choice, switch case decides what functions to call
{
case 1:
cout << "Enter Radius of the circle\n";
radius = input_fun();
calc_area = calc_circle(radius);
return calc_area;
break;
case 2:
cout << "Enter the base of the square\n";
length = input_fun();
calc_area = calc_square(length);
return calc_area;
break;
case 3:
cout << "Enter the length\n";
length = input_fun();
cout << "Enter the width\n";
width = input_fun();
calc_area = calc_rect(length, width);
return calc_area;
break;
case 4:
return 0;
break;
}
}
// This function is activated when user is prompted to
// enter the dimension of the chosen shape.
double input_fun()
{
double value;
cin >> value;
while (value < 0)
{
cout << "Value is lower than 0, try again: \n";
cin >> value;
}
return value;
}
//this function is activated if user chooses a circle.
double calc_circle(double radius)
{
double Pi = 3.14;
double power = 2.0;
return(Pi * pow(radius, power));
}
//this function is activated if user chooses a square.
double calc_square(double base)
{
double power = 2.0;
return(pow(base, power));
}
//this function is activated if user chooses a rectangle.
double calc_rect(double length, double width)
{
return(length * width);
}
void output(double shape, double area)
{
if(shape == 4)
cout << "Have a nice day\n";
else
{
cout << "Shape: " << shape << endl;
cout << "Area: " << area << endl;
}
}

Taking user input from a created class

I'm new to programming, I have been reading Sams Teach Yourself C++ in 24 hours. I just started learning classes and am confused on how to allow user input on private data. I created the following class that returns the area of a Trapezoid. Any suggestions would be greatly appreciated.
class Trapezoid
{
//assigns a number to a variable
private:
int a = 20;
int b = 25;
int height = 30;
int area;
public:
int getArea();
};
int Trapezoid::getArea()
{
// calculates the area and returns it.
area = (a + b) / 2 + height;
return area;
}
#include "AreaTrapezoid.hpp"
#include <iostream>
int main()
{
// accesses area inside the Trapeziod class.
Trapezoid areaT;
areaT.getArea();
// displays the area result
std::cout << "The area of a Trapezoid: " << areaT.getArea() << std::endl;
std::cout << system("pause");
return 0;
}
You need to read the user's input, and then expose public access to assign new values to the class's private members. For example:
class Trapezoid
{
//assigns a number to a variable
private:
int a = 20;
int b = 25;
int height = 30;
public:
int getArea();
void setA(int value);
void setB(int value);
void setHeight(int value);
};
int Trapezoid::getArea()
{
// calculates the area and returns it.
return (a + b) / 2 + height;
}
void Trapezoid::setA(int value)
{
a = value;
}
void Trapezoid::setB(int value);
{
b = value;
}
void Trapezoid::setHeight(int value)
{
height = value;
}
#include <iostream>
#include <limits>
#include <cstdlib>
#include "AreaTrapezoid.hpp"
int main()
{
Trapezoid areaT;
int value;
// get the user's input and apply it to the Trapeziod.
std::cout << "Enter A: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setA(value);
std::cout << "Enter B: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setB(value);
std::cout << "Enter Height: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setHeight(value);
// displays the area result
std::cout << "The area of the Trapezoid: " << areaT.getArea() << std::endl;
std::system("pause");
return 0;
}
Alternatively, use a constructor instead:
class Trapezoid
{
//assigns a number to a variable
private:
int a;
int b;
int height;
public:
Trapezoid(int a, int b, int height);
int getArea();
};
Trapezoid::Trapezoid(int a, int b, int height)
: a(a), b(b), height(height)
{
}
int Trapezoid::getArea()
{
// calculates the area and returns it.
return (a + b) / 2 + height;
}
#include <iostream>
#include <limits>
#include <cstdlib>
#include "AreaTrapezoid.hpp"
int main()
{
int a, b, h;
// get the user's input and apply it to the Trapeziod.
std::cout << "Enter A: ";
std::cin >> a;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter B: ";
std::cin >> b;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setB(value);
std::cout << "Enter Height: ";
std::cin >> h;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// displays the area result
Trapezoid areaT(a, b, h);
std::cout << "The area of the Trapezoid: " << areaT.getArea() << std::endl;
std::system("pause");
return 0;
}

Why does my program output a huge decimal?

Okay so i created program that simulates a landscaping company and so we have to calculate the cost of Sod and fence. So when i enter in both the length and width they out put huge decimals for example
Parkton Landscaping
Enter Length: 10
Enter width: 12
Lanscaping Costs
Sod = 6871947680.00
Fence = 19327352760.00
Press any key to continue . . .
Sod is suppose to = 56.40
and Fence is suppose to = 990.00
please help here is my code and both files
#include <iostream>
#include <iomanip>
using namespace std;
#include "c:\Users\barta\OneDrive\Documents\Visual Studio 2015\Projects\Project 6\Project 6\Geometry.h"
#include "Pricing.h"
int main()
{
int length, width;
Pricing landscape;
Geometry geo;
const double Fenceprice = 22.50;
const double Sodprice = .47;
cout << "\t Parkton Landscaping " << endl;
cout << "Enter Length: ";
cin >> length;
cout << "Enter width: ";
cin >> width;
//Pricing(length, width);
//geo.getLength();
//geo.getWidth();
std::cout << std::fixed << std::setprecision(2);
landscape.displayOutput();
cout << "Sod = " << landscape.getsodCost(length) << endl;
cout << "Fence = " << landscape.getFenceCost(Fenceprice) << endl;
system("pause");
return 0;
}
here is the header file:
#pragma once
class Geometry
{//an object is how you access the class
public:// where the public function definitions are created
Geometry();// Default Constructor
Geometry(int, int);
Geometry(int);
void setLength(int); //assigns length
void setWidth(int); //assigns width
void setSide(int); //assigns side
//Constructor function that recieves the values for the rectangle
//Constructor function that recieves values for the cube
int getLength(),
getWidth(),
getSide(),
getArea(),
getPerimeter(),
getSurfaceArea();
private: //where the private members are created
int length,
width,
side;
void checkNum(int); //function that checks to see if the number is less than 0
};
Geometry::Geometry()
{
length = length;
width = width;
side = 0;
}
Geometry:: Geometry(int length, int width) /*function recieves 2 intergers and calls checkNum to validate if */
{
setLength(length);
setWidth(width);
checkNum(length);
checkNum(width);
}
Geometry:: Geometry(int sides)
{
checkNum(sides);
setSide(sides);
}
int Geometry::getLength()
{
return length;
}
int Geometry::getWidth()
{
return width;
}
int Geometry::getSide()
{
return side;
}
int Geometry::getArea()
{
return length * width;
}
int Geometry::getPerimeter()
{
return 2 * (length + width);
}
int Geometry::getSurfaceArea()
{
return 6 * (side * side);
}
void Geometry::setLength(int len)
{
length = len;
checkNum(len);
}
void Geometry::setWidth(int widths)
{
width = widths;
checkNum(widths);
}
void Geometry::setSide(int s)
{
side = s;
checkNum(s);
}
void Geometry::checkNum(int num) //function checks to see if the number is less than zero
{
if (num <= 0)
{
cout << "!!!!!!!!WARNING!!!!!! this isnt a number" << " program will now exit......" << endl;
system("pause");
exit(1);
}
}
Header file #2
#include "Geometry.h"
class Pricing : Geometry
{
public:
Pricing();
Pricing(int length, int width);
double getsodCost(double);
double getFenceCost(double);
void displayOutput();
private:
};
Pricing::Pricing(int length, int width) :Geometry(length, width)
{
}
Pricing::Pricing()
{
}
double Pricing::getsodCost(double price)
{
getArea();
return getArea()*price;
}
double Pricing::getFenceCost(double price)
{
getPerimeter();
return getPerimeter()*price;
}
void Pricing::displayOutput()
{
cout << "\n\n";
cout << "\t Lanscaping Costs " << endl;
}
Because you never initialize the objects with valid values, meaning Geometry::width and Geogrpapy::length are uninitialized and have indeterminate values. Using them uninitialized leads to undefined behavior.

New to c++, need tips for OOP

I just want to say that this is my first time trying to learn a programming language so excuse my indifference. I am trying to get used to object oriented programming. The problem is I can't figure out how to get what the user inputted without storing it in a public variable.
#include <iostream>
using namespace std;
class Aclass{
public:
void setx(int a){
x = a;
}
void sety(int b){
y = b;
}
void setsum(int c){
c = sum;
}
int getx(){
return x;
}
int gety(){
return y;
}
int getsum(){
return sum;
}
private:
int x;
int y;
int sum;
int diff;
int mult;
int div;
};
int main()
{
string NB;
cout << "What you like to do ?(Sum, Difference, Multiplication or Division)\n";
cin >> NB;
if(NB == "Sum") {
Aclass Ab;
cout << "Enter Your First Number\n";
Ab.setx(cin >> a);
return 0;
}
}
You need to store the user input in a variable, then pass it to Ab.setx to store the variable in the object, i.e.
int main() {
// Declare your variables
Aclass Ab;
string choice;
int x, y;
// Get user choice
cout << "What you like to do? (Sum, Diff, Mul or Div)" << endl;
cin >> choice;
// Get user inputs
if (choice == "Sum") {
cout << "Enter your first number" << endl;
cin >> x; // Get the user input from 'cin' and store it in 'a'
cout << "Enter your second number" << endl;
cin >> y;
// Pass x, y to the Ab object and store them there
Ab.setx(x);
Ab.sety(y);
cout << "The final sum is: " << Ab.getsum() << endl;
}
return 0;
}
Note: the above code requires an implement of getsum as follows:
class Aclass{
// ...
public:
int getsum(){
return (this->x + this->y);
}
// ...

C++ can't populate data

I am trying to populate my vectors with x and y values. but it doesn't seems to add on but just override the
first.
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;
}
how can I make it such that e.g(I enter x and y 3 times let's say 1,1 2,2 3,3 )
then it will output
X: 1,Y: 1
X: 2,Y: 2
X: 3,Y: 3
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;
}
In the function doSomethingWithTheVectorOfPoints, you can place the code for outputting the X and Y coordinates. (You can also just loop through the vector in the main function directly instead.)
Also, you could add a member function to your Point class called ToString or Print to do the work for you.
Edit: I didn't actually compile this, it's just to give you an idea of how you could rewrite your code.
You should have:
No global variables
A point class supporting stream input (output)
The stored data out of the point class (why should a poor point manage that?)
Stream input with validation.
Example:
#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;
}
Note: Throwing exceptions is likely a bad decision, but it simplifies the example.
You re-create your Point object with the final coords every time you enter "no". This is why you only keep the last pair.
On an unrelated note, you should probably simplify the code significantly. There is no reason for Point object to keep a vector of Point objects in the first place. You probably want to keep a history/sequence of raw coordinates there and have something like:
Point mypt;
while (options == "yes") {
mypt.AddCoords(x, y);
// read more coords/options
}
// do stuff on filled mypt object