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;
}
Related
the problem that in the main body the getwhattheywant function is executing twice what I want is this
getwhattheywant execute then the user entered one then if the user entered one do the summation operation but what is happening with me that it's reasking the user to enter a number.
#include <iostream>
using namespace std;
double dothesum(int x, int y)
{
int sum = x + y;
return sum;
};
int getwhatheywant()
{
int choice;
cout << "1- for sum " << endl;
cout << "2- for quit ";
cin >> choice;
return choice;
}
void the_sum()
{
int x, y;
cout << " enter the first number " << endl;
cin >> x;
cout << " enter the second number " << endl;
cin >> y;
cout << " the sum of the two number is " << dothesum(x, y) << endl;
}
int main()
{
int;
while (getwhatheywant() != 2) {
if (getwhatheywant() == 1) {
the_sum();
}
}
return 0;
}
Change your main():
int main()
{
int whatTheyWant;
while ( (whatTheyWant = getwhatheywant()) != 2) {
if (whatTheyWant) == 1) {
the_sum();
}
}
return 0;
}
This stores the value from a single call to getwhattheywant() so you can first see if they're asking to quit, and if not, you can see what else they might want. Now, I'd write it slightly differently:
bool working = true;
while(working) {
int choice = getWhatTheyWant();
switch(choice) {
case 1: the_sum(); break;
case 2: working = false; break;
}
}
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);
}
// ...
I'm very new to programming, I'm just in the 2nd sem of my first year in college so please go easy on the technical terms. We were asked to make a program that reads 10 integers from a file to comprise a list and asks the user to input an integer 'N'. If 'N' is in the list the program should display "FOUND" and "NOT FOUND" if otherwise. I'm getting an error in main about the arguments, it says that 'V', 'N', and 'F' in the function calls "was not declared in this scope".
#include<iostream>
#include<fstream>
using namespace std;
int fRead();
int iRead();
bool search(int, int);
void display(bool);
int main() {
fRead();
iRead();
search(V, N);
display(F);
return 0;
}
int fRead() {
int V[10], c;
ifstream fin;
fin.open("lab02.in");
for(c=0; c<10; c++)
fin >> V[10];
fin.close();
return V[10];
}
int iRead() {
int N;
cout << "Input an integer: ";
cin >> N;
return N;
}
bool search(int V[10], int N) {
bool F = false;
if(V[10] == N)
F = true;
return F;
}
void display(bool F) {
if(F == true)
cout << "\nFOUND" << endl;
else
cout << "\nNOT FOUND" << endl;
}
Local variable (those declared inside a function) are only visible to the block (those things delimited by { and }) where they are declared. If you want to use different functions for various operations you'll need to pass the variables as arguments to the corresponding functions.
As an aside, you should always verify that your read operation was successful before using the result, e.g.:
int N(-1);
if (!(std::cin >> N)) {
std::cout << "ERROR: failed to read integer\n";
}
the integers V N and F are basically described in other functions.
To solve this problem you should declare them in main
the program should go as follows
void f_read(v[]);
void i_read(int &);
bool bool(int,int);
void disp(bool);
void main()
{
int v[10],n;
bool f;
f_read(v);
i_read(n);
f=bool(v,n);
disp(f);
}
void fRead()
{
int c;
ifstream fin;
fin.open("lab02.in");
for(c=0; c<10; c++)
fin >> V[c];
fin.close();
}
void iRead(int &n)
{
cout << "Input an integer: ";
cin >> N;
}
bool search(int V[10], int N)
{
bool F = false;
int i;
for(i=0;i<=9;i++)
if(V[i] == N)
{
F = true;
return F;
}
}
void display(bool F)
{
if(F == true)
cout << "\nFOUND" << endl;
else
cout << "\nNOT FOUND" << endl;
}
so basically you need to pass n as a reference variable and arrays by default are passed as reference.
and also you were looking for v[10]=f ,which would have given you another array, i also corrected that
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
Very new to coding, so please be understanding ;)
I'm basically trying to make a calculator using the while loop, and if statements.
#include <iostream>
using namespace std;
int x = 1;
int number;
int total = 0;
int amt = 1;
int a;
int b;
int c;
int d;
string ans;
class OperateClass
I get the error: two or more data types in declaration of 'main'
Please explain what this means/how to fix it.
I was also wondering if I need to make a new object for each function (Add, subtract, multiply, and divide)
Please help!
int main()
{
cout << "Do you want to add, subtract, multiply or divide? I want to : " << endl;
cin >> ans;
if(ans == "add"){
OperateClass opOper;
opOper.add();
}else{
if(ans == "subtract"){
OperateClass opOper
opOper.subtract();
}
}else{
if(ans == "multiply"){
OperateClass opOper
opOper.multiply();
}
}else{
if(ans == "divide"){
OperateClass opOper
opOper.divide();
}
}
}
class OperateClass{
public:
int add(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> a;
total = total + a;
x++;
amt++;
}
}
int subtract(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> b;
total = total - b;
x++;
amt++;
}
}
int multiply(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> c;
total = total * c;
x++;
amt++;
}
}
int divide(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> d;
total = total / d;
x++;
amt++;
}
}
}
int print(){
cout << "Your total is: " << total << endl;
return 0;
}
None of that code is valid. You begin a class definition with class OperateClass, but never end it and run right into main. A (simplified) class definition takes the form of:
class [name] {
}; // semi-colon terminates definition
// so...
class OperateClass {
};
Next, you declare main... but it leads to an else branch (?).
int main()
{
cout << "Do you want to add, subtract, multiply or divide? I want to : " << endl;
cin >> ans;
if(ans == "add"){
OperateClass opOper;
opOper.add();
}else{ // what is this?
Functions must also terminate via their closing brace, i.e.,
int main() {
} // function is over!
Now it looks like those may just be copy/paste errors. If that's the case then you probably just forgot the semi-colon at the end of the class definition.
Consider the following program:
class C
int main() {
}
class C {
}
void someFunc(){}
This is basically your program boiled down to the necessities. Here are the errors:
error: two or more data types in declaration of 'main'
error: expected ';' after class definition
Here's the corrected code:
class C; //<--semicolon in forward declaration
int main() {
}
class C {
}; //<--semicolon after class definition
void someFunc(){}
Lets make a slight modification of your code so that your syntax is right.
int main()
{
cout << "Do you want to add, subtract, multiply or divide? I want to : " << endl;
cin >> ans;
if(ans == "add"){
OperateClass opOper;
opOper.add();
}
else if (ans == "subtract"){
OperateClass opOper;
opOper.subtract();
}
else if (ans == "multiply"){
OperateClass opOper;
opOper.multiply();
}
else if(ans == "divide"){
OperateClass opOper;
opOper.divide();
}
else {}
} //end of main
Your class variable declaration statement "OperateClass opOper" also repeats in each case, you could also just write that statement outside your if-else conditions to avoid repetition since that statement is true regardless of any case.