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
Related
I'm new to C++ and stack overflow in general so please excuse me if a make a mistake somewhere.
I posted my code down below, but my issue is that when I type either yes or no at after the calculation is complete, no is supposed to end the program (which I was still working on) and yes is supposed to set it up for another calculation.
However I end up with a glitchy loop.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
bool b;
bool yes = b;
do {
float x;
float y;
float z;
float a;
cout << "Enter The amount you are investing:" << endl;
cin >> x;
cout << "Enter the rate:" << endl;
cin >> y;
cout << "Enter the investment period (years):" << endl;
cin >> z;
cout << "Enter the compounding period:" << endl;
cin >> a;
cout << pow((1 + y / a), (a*z))*x << endl << "Want to do another? (yes/no)";
cin >> b;
cin.ignore();
} while (yes = true); {
cin.clear();
if (b = yes) {
}
else {
}
}
return 0;
}
The behaviour of your code is probably due to:
unintentional reassignment of the termination condition bool value: yes to: true, instead of checking its value, which is done with ==, not with the assignment =.
no modification of the value yes within the while loop.
A possible update is:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// initialise the sentinel
bool yes = true;
do {
// define variables
float x, y, z, a;
// read input
cout << "Enter The amount you are investing:" << endl;
cin >> x;
cout << "Enter the rate:" << endl;
cin >> y;
cout << "Enter the investment period (years):" << endl;
cin >> z;
cout << "Enter the compounding period:" << endl;
cin >> a;
cout << pow((1 + y / a), a * z) * x << endl;
// redo calculation or exit
cout << "Want to do another? (yes/no)";
cin >> yes;
// check termination condition
} while (yes == true);
return 0;
}
Additionally, watch out for the uninitialised variables: x, y, z, a and think for a proper default value that will indicate possible wrong result.
Lastly, withing the calculation: 1 + y / a is ambiguous, it could mean both: (1 + y) / a and: 1 + (y / a), put parentheses to enforce precedence in the wanted order.
You are not modifying the value of variable yes. It is always set to true.
I am designing a Logic Gate data structure in C++ called AND that has 3 functions:
a function that takes input either 1 or 0 from the user.
a function that shows output of AND Gate from the input.
a function that asks user if they want to edit their inputs and if yes, then allows them to edit the inputs they have entered.
Problem is that I cannot figure out how to call the function that edits input in the main. Following is my code.
#include<iostream>
using namespace std;
struct AND //structure called AND
{
int x, y;
AND() //constructor
{
x, y = 0; //declaring variables as inputs
}
void inputAND() //function that takes inputs from the user
{
cin >> x;
cin >> y;
}
void outputAND() //function that displays output
{
if (x == 0 || y == 0)
{
cout << "0" << endl;
}
else if (x == 1 && y == 1)
{
cout << "1" << endl;
}
}
void changeInputAND(AND change[]) //function for changing inputs
{
cout << "Do you wish change first input Yes/No:" << endl;
string t;
cin >> t;
int k;
if (t == "Yes" || "yes")
{
cout << "Enter New Input ";
cin >> k;
x = k;
}
else
{
k = x;
}
cout << "Do you wish to change the second input Yes/No:" << endl;
{
string s;
cin >> s;
int l;
if (t == "Yes" || "yes")
{
cout << "enter new input";
cin >> l;
y = l;
}
}
}
};
void main()
{
AND a1;
a1.input(); //calling the input function
a1.output(); //calling the output function
}
Suggestions for improvement and how to implement the task of editing an AND object.
Keep your class as simple as you can. Don't pollute it with code related input and output streams.
struct AND //structure called AND
{
int x, y;
AND() : x(0), y(0) //constructor
{
}
void setX(int newX)
{
x = newX;
}
void setY(int newY)
{
y = newY;
}
};
Initialize members of a class in the initializer list instead of assigning to them in the body of a constructor.
Prefer to use:
AND() : x(0), y(0) //constructor
{
}
over
AND() //constructor
{
x = y = 0;
}
Move the code to read and write from member functions to non-member functions. Don't assume whether the input/output streams are std::cin or std::cout. The driver code can choose to use std::cin/std::cout or it may choose a file, std::ifstream/std::ofstream.
// Write data to a stream
std::ostream& operator<<(std::ostream& out, AND const& a)
{
return out << a.x << " " << a.y;
}
// Read data from a stream
std::istream& operator>>(std::istream& in, AND& a)
{
in >> a.x >> a.y;
}
Also, it's better to make sure that write/read are such that what is written out can be read back.
Create a non-member function for reading user data and changing the object instead of putting it all in a member function.
// Non-member function for changing the object.
void changeInputAND(AND& a)
{
cout << "Do you wish change first input Yes/No:" << endl;
string ans;
cin >> ans;
if (ans == "Yes" || ans == "yes")
{
cout << "Enter New Input ";
int x;
cin >> x;
a.setX(x);
}
cout << "Do you wish to change the second input Yes/No:" << endl;
cin >> ans;
if (ans == "Yes" || ans == "yes")
{
cout << "enter new input";
int y;
cin >> y;
a.setY(y);
}
}
BTW, your attempt at comparing with "Yes" or "yes" is flawed.
if (ans == "Yes" || "yes")
is equivalent to
if ( (ans == "Yes") || "yes")
That will always evaluate to true. That's a very different topic :)
Put it all together in one or more functions to test the AND functionality, preferably different from main.
void testAND()
{
AND a1;
std::cin >> a1; // calling the input function
std::cout << a1 << std::endl; // calling the output function
changeInputAND(a1); // function for changing inputs
std::cout << a1 << std::endl; // calling the output function again
}
Call the test function from main.
void main()
{
testAND();
return 0;
}
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);
}
// ...
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!
Not very good at debugging yet but I'm getting a few errors. A few expected '(' ')' and ';'
Also 'else' without a previous 'if', no match for 'operator>>' in cout
I know this is easy, but still trying to get my foot in the door. Thanks :)
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // guess number game
{
int x;
cout >> "Please enter a number\n";
getline(cin x);
int y = rand();
while x != y
{
if x < y;
cout >> "Go higher";
else;
cout >> "Go lower";
}
}
cout >> "Please enter a number\n";
This is wrong, std::ostreams only provide the operator<< to insert formatted data. Use cout << "Please enter a number\n"; instead.
getline(cin x);
First, you're missing a ,, since getline needs two or three arguments. But since x is an integer and not a std::string it is still wrong. Think about it - can you store a text line inside of an integer? Use cin >> x instead.
int y = rand();
While this doesn't seem wrong there's a logical error. rand() is a pseudo random number generator. It uses a seed as start value and some kind of algorithm (a*m + b). Thus you have to specify a start value, also called seed. You can specify this by using srand(). The same seed will result in the same order of numbers, so use something like srand(time(0)).
while x != y
if x < y;
Use parenthesis. And drop the additional ;. A stray semicolon ; in your program resembles the empty expression.
EDIT: Working code:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main(){
int x;
int y;
srand(time(0));
y = rand();
std::cout << "Please enter a number: ";
do{
if(std::cin >> x){
if(x < y)
std::cout << "Go higher: ";
if(x > y)
std::cout << "Go lower: ";
}
else{
// If the extraction fails, `std::cin` will evaluate to false
std::cout << "That wasn't a number, try again: ";
std::cin.clear(); // Clear the fail bits
}
}while(x != y);
std::cout << "Congratulations, you guessed my number :)";
return 0;
}
Try this:
void main()
{
int x;
cout << "Please enter a number\n";
getline(cin, x);
int y = rand();
while(x != y)
{
if(x < y)
cout << "Go higher";
else
cout << "Go lower";
}
}
Not overly familiar with C++ but i'm pretty sure the while/if should look something like this
while (x != y)
{
if (x < y)
cout << "Go higher";
else
cout << "Go lower";
}
the conditions of both if and while loops should be nested with parenthesis.
everything you listed above are syntax errors. This can be easily fixed by reading up on the syntax of c++
http://www.cs.duke.edu/csed/tapestry/howtoa.pdf
it should look more like this:
while (x != y)
{
if (x < y)
cout >> "Go higher";
else
cout >> "Go lower";
}
Let's look at all the errors:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // guess number game
{
int x;
cout >> "Please enter a number\n"; // should be `cout <<` cin uses >>
getline(cin x); // incorrect number of arguments should be 2 or 3 plus x is an int not string could use cin instead
int y = rand();
while x != y // error condition checks should be parentheses like (x != y)
{
if x < y; // error condition should be parentheses also by adding a semicolon here you terminate the statement
cout >> "Go higher";
else; // technically not an error but unintended code is executed cout >> "Go higher" is always executed because of the semi colon ;
cout >> "Go lower";
}
// no return of value, you declared main to return an int so you should
}
Try this:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // guess number game
{
int x;
cout << "Please enter a number\n";
cin >> x;
int y = rand();
while (x != y)
{
if (x < y)
cout >> "Go higher";
else
cout >> "Go lower";
}
return 0;
}