deal data of any datatype in c++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
This problem will solve that you can deal with any datatype in c++.
I will solve it with the help of template classes in c++.
first, we create the two template class in my case I will name them T1 and T2and in the class,
I will declare no variables with that T1 & T2 class then write a function that can cin the value from the user and further in the main body when I create an object of that class so I will start the object as string data type.  
#include <bits/stdc++.h>
using namespace std;
template < class T1 = float , class T2 = float >
class Hamza{
T1 a;
T2 b;
float e = 0, f = 0;
public:
Hamza(T1 o1, T2 o2) {
cout << "Enter 1st Val Of Any Datatype = ";
cin >> a;
cout << "Enter 2nd Val Of Any Datatype = ";
cin >> b;
istringstream(a) >> e;
istringstream(b) >> f;
}
~Hamza() {
if ( e != 0 && f != 0 )
cout << "THE SUM IS = [ " << a << " + " << b << " ] = " << e + f << endl;
else
cout << "THE SUM IS = [ " << a << " + " << b << " ] = " << a + b << endl;
}
};
int main()
{
system("CLS");
up:
Hamza <string , string> obj(" ", " ");
goto up;
}

Related

Why is it not changing values of that variables? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to change this program so that data of object star show actually name and nr_indeksu but i'am stuck. Any help? And sorry for variables names but in my laguage they have meaning believe me and for the mess.
#include <iostream>
using namespace std;
class student
{
private:
string imie_nazwisko_ = "NO_NAME";
unsigned int nr_indeksu_ = 0;
public:
student(string imie_nazwisko, unsigned int nr_indeksu);
void printDane()
{
cout << " Metoda printDane klasy bazowej" << endl;
cout << " imie nazwisko " << imie_nazwisko_ << endl;
cout << " nr indeksu " << nr_indeksu_ << endl;
}
};
class starosta : public student
{
public:
string imie_nazwisko_ = "NO_NAME";
unsigned int nr_indeksu_ = 0;
string email_ = "no#noemail";
void printDane()
{
cout << " Metoda printDane klasy starosta" << endl;
cout << " imie nazwisko " << imie_nazwisko_ << endl;
cout << " nr indeksu " << nr_indeksu_ << endl;
cout << " email "<< email_<<endl;
}
starosta(string imie_nazwisko, unsigned int nr_indeksu, string email);
};
starosta::starosta(string imie_nazwisko, unsigned int nr_indeksu, string email) :student(imie_nazwisko, nr_indeksu), email_(email)
{
cout << "Tworzenie obiektu klasy starosta "<< endl;
}
student::student(string imie_nazwisko, unsigned int nr_indeksu) : imie_nazwisko_(imie_nazwisko)
{
nr_indeksu_ = nr_indeksu;
cout << "Tworzenie obiektu klasy student" <<endl;
}
int main()
{
student stud("Jan Kowalski",7);
stud.printDane();
starosta star("Aleksandra Nowak",999,"mail#nomail.dot");
cout << "Dane:" << star.imie_nazwisko_ << " " << star.nr_indeksu_ << endl;
star.printDane();
}
You declare new members in the class starosta that already exist in the class student. Then you initialize the members of student using its constructor and try to print out the members of starosta in its method printDane. You should remove duplicated names from the class starosta.
class starosta : public student
{
public:
string imie_nazwisko_ = "NO_NAME"; // duplicates student::imie_nazwisko_
unsigned int nr_indeksu_ = 0; // duplicates student::nr_indeksu_

Printing an object after putting it into a map [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
class Task
{
public:
string study;
int time;
bool made;
int priority;
}
class Day
{
public:
string date = "undefined";
int aims = 0;
vector <Task> tasks;
}
i have 2 classes,where i use vector to keep data from both.
this project is a daily planner for one day.
Now i need to improve it to store more days,tutor wants me to use MAP.
map<string, Day>Days;
map<string, Day>::iterator it;
Days.insert(pair<string, Day>(s, d));
for (it = Days.begin(); it != Days.end(); ++it)
{
cout << it->first << " " << it->second << '\n';
}
E0349 missing operator "<<" corresponding to these operands
C2679 binary "<<": no operator was found that accepts a right operand of type "_Ty2" (or there is no acceptable conversion)
with
[_Ty2 = Day]
how can I do this?
void PrintDay(const Day& d, ChangeF Pd)
{
cout << "Current date:" << d.date << endl << "\n=============================================" << endl << "Number of tasks:" << d.aims;
cout << "\n=============================================" << endl;
for (int i = 0; i < d.aims; i++)
{
PrintTask(d.tasks[i], Pd);
}
}
Day InputDay()
{
setlocale(LC_ALL, "Russian");
Day d;
cout << "\nEnter date dd ENTER mm ENTER yyyy ENTER obe by one" << endl;
int dd, mm, yyyy;
dd = DigitInputCheck(1, 30);
mm = DigitInputCheck(1, 12);
yyyy = DigitInputCheck(0, 4000);
ostringstream WriteDate;
WriteDate << dd << "." << mm << "." << yyyy << endl;
d.date = WriteDate.str();
cout << "Number of tasks:" << endl;
cin >> d.aims;
for (int i = 0; i < d.aims; i++)
{
d.tasks.push_back(InputTask());
}
return d;
}
As mentioned in the comments, you need to overload the operator<< for the type Day if you are going to try to use << with it. Since you already have a PrintDay, I'll adapt it to work with the operator. I have no idea what Pd is supposed to be, so I'm ignoring it. This function should be a global function. Since all your fields are public, it doesn't need special access via friend either.
std::ostream &operator<<( std::ostream &os, const Day &day ) {
os << "Current date:" << d.date << '\n'
<< "\n=============================================\n"
<< "Number of tasks:" << d.aims
<< "\n=============================================\n";
for (int i = 0; i < d.aims; i++)
{
os << d.tasks[i];
}
}
You would also need to add the operator for your Task type as well. Given the above, you should be able to make another function for your PrintTask function.

Is it okay to have many parameters in a void function in C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm a beginner so please be nice :)
I already make the program work properly with the use of Global Variables. But I want to try using Local Variables because the Global Variables looks messy and I also found out that it is a bad practice to always use it. The program runs with the Local Variables but it doesn't work properly. I'm having a problem with the display of the results which is under the void function funcDataSummary. The void funcDataSummary works and the values of (float numberOfRooms, float wallSpace, float costOfPaint,...) which are inputted by the user is correct but the values of (..., float gallonsOfPaint, float totalCostOfPaint, float hoursOfLabor, float laborCost, float totalCost) is 0 when they should have a value.
Output with the use of Global Variables:
Output with the use of Local Variables:
#include <iostream>
#include <iomanip>
#include <windows.h>
using namespace std;
// function prototype
void funcDataSummary(float, float, float, float, float, float, float, float);
// void function called in int main()
funcDataSummary(numberOfRooms, wallSpace, costOfPaint, gallonsOfPaint, totalCostOfPaint, hoursOfLabor, laborCost, totalCost);
// void function
void funcDataSummary(float numberOfRooms, float wallSpace, float costOfPaint, float gallonsOfPaint, float totalCostOfPaint, float hoursOfLabor, float laborCost, float totalCost)
{
cout << "DETAILS" << endl;
cout << "Number of Rooms = " << funcNumberOfRooms(numberOfRooms) << endl;
cout << "Wall Dimension = " << funcWallSpace(wallSpace) << " square feet" << endl;
cout << "Paint Cost = Php " << funcCostOfPaint(costOfPaint) << endl;
cout << "Gallons of Paint = " << funcGallonsOfPaint(gallonsOfPaint);
// singular and plural forms of units
if(funcGallonsOfPaint(gallonsOfPaint) > 1)
{
cout << " Gallons" << endl;
}
else
{
cout << " Gallon" << endl;
}
cout << "Total Paint Cost = Php " << << funcTotalCostOfPaint(totalCostOfPaint) << endl;
cout << "Labor hours = " << funcHoursOfLabor(hoursOfLabor);
// singular and plural forms of units
if(funcHoursOfLabor(hoursOfLabor) > 1)
{
cout << " hours" << endl;
}
else
{
cout << " hour" << endl;
}
cout << "Labor Cost = Php " << funcLaborCost(laborCost) << endl;
cout << "TOTAL COST = Php " << funcTotalCost(totalCost) << endl;
}
Though it's okay, it makes your code a bit complicated.
If it's possible, it's better group related to each other variables in one or more struct or class and pass these objects (or pointer/reference/const reference if it is needed) as parameters.
My suggestion is to use immutable class to store all kind of stuff you need in your function and pass it as a const reference or pointer. Here is an example :
#include <iostream>
#include <string>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
class ParamsHolder : private boost::noncopyable
{
private :
std::string m_name;
std::uint32_t m_value;
public :
typedef boost::shared_ptr<ParamsHolder> pointer;
ParamsHolder( const std::string name, std::uint32_t value )
: m_name( name ), m_value( value ) {}
virtual ~ParamsHolder() {}
std::string getHolderName() const { return m_name; }
std::uint32_t getHolderValue() const { return m_value; }
};
void testFunction( ParamsHolder::pointer holder )
{
std::cout << holder->getHolderName() << std::endl;
std::cout << holder->getHolderValue() << std::endl;
}
int main()
{
std::cout << "Test program for holder" << std::endl;
std::string testName = "some name";
std::uint32_t testValue = 111;
auto holder = boost::make_shared<ParamsHolder>( testName, testValue );
testFunction( holder );
return 0;
}
To create a holder with many parameters have a look at builder design pattern or abstract factory.

c++ function redefining (code not working - logic error)

I am currently learning c++ and i am now working on Inheritance.
I have to make a regular question class as well as a derived class that is a Numeric question and a multiple choice question. I make the questions in the code, and then display them 1 by 1 to the user. The user then answers the questions, and the program is supposed to check whether the answer is correct.
#include <iostream>
#include <string>
using namespace std;
class Question {
protected:
string text;
string answer;
string input;
public:
Question(string inText, string inAnswer) {
text = inText;
answer = inAnswer;
}
Question() {
text = "blank question";
answer = " ";
}
void setQuestion(string txt) {
text = txt;
}
void setAnswer(string answr){
answer = answr;
}
void userAnswer(string ans) {
input = ans;
}
string getAnswer() {
return answer;
}
string getQuestion() {
return text;
}
void displayQuestion() {
cout << getQuestion() << endl;
}
void isCorrect() {
cout << "default function" << endl;
if (input.compare(answer) == 0)
cout << "True" << endl;
else
cout << "False" << endl;
}
};
class NumericQuestion : public Question {
protected:
double ans;
double inp;
public:
NumericQuestion(string inText, double inAns) {
text = inText;
ans = inAns;
}
void userAnswer(string ans) {
inp = stod(ans);
}
void isCorrect() {
cout << "numeric function" << endl;
if (inp == ans)
cout << "True" << endl;
else if ((inp - ans) <= 0.01)
cout << "False" << endl;
else
cout << "False" << endl;
}
};
class MultipleChoice : public Question {
protected:
string qA, qB, qC, qD;
public:
MultipleChoice(string inText, string qA, string aB, string qC, string qD, char inAnswer) {
text = inText;
answer = inAnswer;
}
void displayQuestion() {
cout << text << endl;
cout << "a) " << qA << " " << "b) " << qB << endl;
cout << "c) " << qC << " " << "d) " << qD << endl;
}
};
int main() {
string ans;
Question q1("whats 2+2", "four");
NumericQuestion q2("2+2", 4);
MultipleChoice q3("The Right Answer is C", "answer A", "thisisB", "thats C", "Wrong", 'c');
Question arr[] = { q1,q2,q3};
for (int i = 0; i < 3; i++) {
arr[i].displayQuestion();
cin >> ans;
arr[i].userAnswer(ans);
arr[i].isCorrect();
}
getchar();
return 0;
}
The member function isCorrect() from NumericQuestion class and displayQuestion() from MultipleChoice class don't get used, instead, the ones from Question class get used, which lead to logical errors in my code.
You're slicing objects when you assign subclasses of Questions by value to an array of Question when you do Question arr[] = { q1, q2, q3 };. This means that even though some of your derived Question objects have extra members that the base class doesn't, they're being truncated away by the assignment into the array. Another problem is that because arr is declared to hold plain and simple Question objects, the compiler will assume that a call like arr[i].isCorrect(); will always refer to Question::isCorrect(), and not a derived method. Here's a couple things to fix.
Make overridable functions virtual:
class Question {
...
virtual void isCorrect() {
cout << "default function" << endl;
if (input.compare(answer) == 0)
cout << "True" << endl;
else
cout << "False" << endl;
}
and override them in subclasses:
class NumericQuestion : public Question {
...
void isCorrect() override {
cout << "numeric function" << endl;
if (inp == ans)
cout << "True" << endl;
else if ((inp - ans) <= 0.01)
cout << "False" << endl;
else
cout << "False" << endl;
}
Finally, avoid the slicing by storing base class pointers to your Questions. Here, I'm using std::shared_ptr to avoid the headaches of manual memory management. Also appearing is a ranged-for loop:
auto q1 = std::make_shared<Question>("whats 2+2", "four");
auto q2 = std::make_shared<NumericQuestion> q2("2+2", 4);
auto q3 = std::make_shared<MultipleChoice>("The Right Answer is C", "answer A", "thisisB", "thats C", "Wrong", 'c');
// even though q1...q3 are shared_ptrs to derived classes, they can be safely cast to shared_ptrs to the base class
std::vector<std::shared_ptr<Question>> questions { q1, q2, q3 };
for (const auto& question: questions) {
question->displayQuestion();
cin >> ans;
question->userAnswer(ans);
question->isCorrect();
}
You need to set userAnswer, displayQuestion and isCorrect as virtual in the base class.
You also need to store your question as pointers (there's other options) to prevent slicing. Personally, I find it simpler to fix it like this:
Question* arr[] = {&q1,&q2,&q3};
...
arr[i]->displayQuestion();
(you need to change all usage or arr[i] to use arrows)
There are two issues at play here.
1) Based on your for loop at the end, you need to declare some functions, like displayQuestion(), userAnswer(), and isCorrect() as virtual.
2) Secondly, change your arr declaration to Question *arr[] = {&q1, &q2, &q3};.

cardano's method in c++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i am trying to make a program that will compute for the root of a cubic function using cardano's method
here's my code:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a, b, c, d, value;
double f, g, h;
double i, j, k, l, m, n, p, po;
double r, s, t, u;
double x1, x2, x2re, x2im, x3re, x3im, x3;
cin >> value;
for(int w=1; w <= value; w++){
cin >> a >> b >> c >> d;
cout << "CUBIC EQUATION : " << a << " x^3 + " << b << " x^2 + " << c <<" x + " << d << " = 0" << endl;
f = ((3*c/a)-((b*b)/(a*a)))/3;
g = ((2*(b*b*b)/(a*a*a))-(9*b*c/(a*a))+(27*d/a))/27;
h = ((g*g)/4)+((f*f*f)/27);
if(f==0 && g==0 && h==0){ // all roots are real and equal
x1 = pow((d/a),0.33333333333333333333333333333333);
x2 = pow((d/a),0.33333333333333333333333333333333);
x3 = pow((d/a),0.33333333333333333333333333333333);
cout << "x = " << x1 << endl;
cout << "x = " << x2 << endl;
cout << "x = " << x3 << endl;
}
else if(h<=0){ // all 3 roots are real
i = pow((((g*g)/4)-h),0.5);
j = pow(i,0.33333333333333333333333333333333);
k = acos((g/(2*i))*-1);
l = j * -1;
m = cos(k/3);
n = sqrt(3) * sin(k/3);
p = (b/(3*a))*-1;
x1 = (2*j)*m-(b/(3*a));
cout << "x = " << x1 << endl;
x2 = l * (m+n) + p;
cout << "x = " << x2 << endl;
x3 = l * (m-n) + p;
cout << "x = " << x3 << endl;
}
else if(h>0){
r = ((g/2)*-1)+pow(h,0.5);
s = pow(r,0.33333333333333333333333333333333);
t = ((g/2)*-1)-pow(h,0.5);
u = pow((t),0.33333333333333333333333333333333);
x1 = (s+u) - (b/(3*a));
cout << "x = " << x1 << endl;
x2re = (((s+u)*-1)/2) - (b/(3*a));
x2im = -(s-u)*pow(3,0.5)/2;
cout << "x = (" << x2re << "," << x2im << ")" << endl;
x3re = (((s+u)*-1)/2) - (b/(3*a));
x3im = (s-u)*pow(3,0.5)/2;
cout << "x = (" << x3re << "," << x3im << ")" << endl;
}
}
return 0;
}
can anyone help implement a user-defined ComplexNumber in this code?
I want to use this link http://en.wikipedia.org/wiki/Cubic_function but i cant understand this.
can anyone help implement a user-defined ComplexNumber in this code?
Don't implement a user-defined ComplexNumber type. Use the one provided by the language. Just #include <complex>. With that you can have a complex variable simply by complex<double> variable_name.
Code comments:
It's better to use std::sqrt(x) rather than std::pow(x, 0.5).
If you are on a POSIX-compliant machine, your math library has a cube root function, cbrt(double) in the header . (It may not be exported to the C++ header .) This too is preferable over std::pow(x,0.33333333333333333333333333333333).