Hey Jackk, I don't know if you been drinking Jack or something, but you need to watch
your manners. This isn't your house, so you don't get to shout or demand.
mrnutty 761 Senior Poster
Hey Jackk, I don't know if you been drinking Jack or something, but you need to watch
your manners. This isn't your house, so you don't get to shout or demand.
No code?
Sorry I don't release code. Although, I can post small snippets if anyone wants to ask something.
Yea, here is a mediocre way :
#include <ctime>
#include <iostream>
using namespace std;
void runFunctionHere(){}
int main(){
long start = clock();
runFunctionHere();
long end = clock();
cout << "Time took in milli seconds : " << end - start << endl;
}
Just a beta of what I was working on lately. It evaluates mathematical expressions like 2*3. Anyways, its explained in the program. Report of any bugs would be great because I haven't tested it out that much. Without further ado, you can download the program here, here or here.
Try the last one first, it has less ads, hopefully. Thanks for helping.
You can use some math magic. Or you can get the input as a string, which is much easier.
For example here is some not tested code. It gets the input as a string. Then
sums the digits inside the string. And displays it.
string digits;
cin >> digits;
int sum = std::accumulate(digits.begin(),digits.end()) - digits.size() * '0';
for(int i = 0; i != digits.size() - 1; ++i){
cout << digits[i] <<" + ";
}
cout << digits[digits.size()-1] << " = " << sum << endl;
Does it have to be in C++? Can you use external libraries?
That's nothing a quick google can't help you with. But since you asked here it is :
#include <iostream>
#include <ctime>
using namespace std;
int main(){
srand(time(0));
for(int i = 0; i != 10; ++i){
cout << rand() << endl;
}
}
Maybe my statement of having getters and setters leads to bad design, was taken a
little to the extreme. And it was my fault that I didn't point out the implicit implication
that I though was obvious for me. So let me clarify, if one has a lot of getters and setters,
its usually a hint of bad design. There are always cases where having the necessary getters and
setters are a need. It is up to the user to decide if having them is worth it?
I am not saying using getters and setters are necessarily bad in itself. I am just saying that
it could be a symptom of a bad design and usually is. And that one should really think
whats the advantage it provides. And does it necessarily need to be part of the interface?
>>You can include logging, or debug output without any trouble, whereas if the data members are public/protected, life becomes harder
Yes I hear the debugging argument from time to time. But from the little information
I got from the OP's code. It does not seem like the type that needs logging.
I mean its a good thing to be able to put breakpoints and perform validation on data members,
but doesn't it seem like its decreasing encapsulation a bit? Its simply letting the properties of the
object available to the public interface.
I mean if OP is looking for "good object oriented design" then I disagree that having
getters and setters is a good thing. One can avoid getters and setters by having a
better design.
If tp is going to be altered, like that then why even have getter/setters? Its
pointless.
If you know the input is going to be something like, hour:min:sec then you can just
read it from the stream, and discard the ":" character into a variable or something.
int main(){
int h(0),m(0),s(0)
char tmp = 0;
cin >> h >> tmp >> m >> tmp >> s;
cout << h << endl << m << endl << s << endl;
}
Yes I did, and I showed you what you should have done. What you did made no sense.
Every animal has a name,weight, and age. Thus the animal class should contain all.
Instead of defining a operator<< for all three, you only need to define one operator<<.
So you see your structures does not really make sense. But to answer your question,
yes that is one way you can and did achieve what you wanted.
What you are doing is hard coding each stream insertion operator. This is what you want :
struct Animal{
int weight, age;
string name;
Animal(string name = "", int weight = 0, int age = 0)
: name(name), weight(weight), age(age){}
~Animal()=0{}
};
struct Mammal : Animal{
};
struct Dog : Mammal{
};
std::ostream& operator>>(std::ostream& outStream, const Animal& animal){
outStream << "Name : " << animal.name << "\n";
outStream << "Weight : " << animal.weight << "\n";
return outStream << "Age : " << animal.age << "\n";
}
int main(){
Dog dog("Rudolph",150,7);
cout << dog << endl;
}
Something like this should suffice, although you might want something better :
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
struct SimpleTime{
int hours;
int minutes;
int seconds;
SimpleTime(int h = 0, int m = 0, int s = 0)
: hours(h), minutes(m), seconds(s) {}
};
//does no error check
SimpleTime praseStrTime(const std::string& timeStr, char delim ){
string::size_type hourPos = timeStr.find(delim);
string::size_type minPos = timeStr.find(delim,hourPos+1);
string hours = timeStr.substr(0,hourPos);
string minutes = timeStr.substr(hourPos+1,(minPos - hourPos - 1));
string seconds = timeStr.substr(minPos+1);
stringstream stream( hours + " " + minutes + " " + seconds );
int timeArray[3] = {0};
int index = 0;
while(stream >> timeArray[index++]) continue;
return SimpleTime(timeArray[0],timeArray[1],timeArray[2]);
}
void printTime(const SimpleTime& t){
cout << "hours = " << t.hours << endl;
cout << "minutes = " << t.minutes << endl;
cout << "seconds = " << t.seconds << endl;
}
int main(){
string input = "09:12:59"; //hours:minutes:seconds
printTime( praseStrTime(input,':') );
return 0;
}
>>ran but the output was zeros for all the generated random numbers
Thats because rand()/RAND_MAX yields 0 because of integer division. You need to
promote it to this : rand() / float(RAND_MAX)
What you are looking for is polymorphism. This example should answer your question :
struct Polygon{
int width,height;
virtual int area()const = 0;
};
struct Rect : Polygon{
int area()const{ return width * height; }
};
struct Triangle : public Polygon{
int area()const{ return width*height*0.5f; }
}
//notice input could be any class that derives from Polygon class
void printArea(const Polygon& p){
cout << p.area() << endl;
}
int main(){
Rect r;
r.width = 5;
r.height = 5;
Triangle t;
t.width = 6;
t.height = 3;
printArea(r);
printArea(t);
}
You don't need to use the ignore function, you can just do something like this :
const int SPACE = ' ';
//peek the next character to see if its a space, if so then discard it
if(cin.peek() == SPACE) cin.get(); //opt #1
char ch = 0;
cin.get(ch); //Opt # 2
if(ch != SPACE){ /*do something */ }
//opt #3
string term;
cin >> term; //read in a term and skip white spaces
prase(term);
//Hint on opt # 4
stringstream ss("3x^6 + 2x^2 + 9");
string str;
while(ss >> str){
cout << str << endl; //prints each term
}
First this code will show you what type null is :
cout << "NULL type is " << typeid(NULL).name() << endl;
cout << "NULL value is " << NULL << endl;
This is the output you will probably get :
NULL type is int
NULL value is 0
Second this code :
if(strlen(str)==0)
checks if the length of the string str is 0. The function strlen returns the
length of the null terminated string passed to it.
And in code str[]="". The length of str is 0. It contains only the null-terminated character, which does not count of the actual length of str.
And last of all, avoid all of these complication by using std::string. Unless you
are doing this as practice or something.
Do you really need to use the "==" operator. Can you settle for something like this :
typedef pair<int,int> IntPair;
bool hasEqualSecond(const IntPair& lhs, const IntPair& rhs){
return lhs.second == rhs.second;
}
//....
if(hasEqualSecond(p1,p2)){ /*do something */ }
@OP: whenever you use const_cast, you have a serious design and logic problem in your
code. The cases are very very rare, where it would justify to use const_cast in a
program, and I assure you that you case is not one of them.
What does this function do,
int Activate ( int &tp, int weaponDamage, int attack );
Is it supposed to initialize the data? Why is tp pass by reference? Does it
necessarily have to be passed by references? Should activate be a member function?
Instead of watching you accept a bad advice just to "get it working", I'd rather you
leave with a good advice and a better design.
>>It occurred to me that this only generates numbers uniformly over the range
In fact, it dosen't. The only way rand() generate uniform distribution is by using the
value it returns as the random number and not manipulate that random number. Thus
when you do something like this : int power = rand()/(RAND_MAX) * (max-min)
you are affecting the distribution. See here for more details.
Also here (a / 32767) * (upper - lower); // RAND_MAX for MS VC++ Express is 32,767.
Instead of saying 32767 is RANDMAX in vc++, just use RANDMAX as the constant. Not
only that will make it clearer, it will be easier to maintain, since say for some reason RAND_MAX was something else later on for whatever reason, now your gonna have
to relocate all usage of 32767 and change it as well. If you want a better distribution then you will have to look at other libraries. rand() usually is good enough for most of your applications, but when you get serious, then you will want to
look at other libraries that have been throughly tested. And forget about creating your own RNG. There is no point.
>>of course the first one is the simplest, best and most efficient
"Simplest and best" are subjective terms. And about it being efficient, not completely sure about that. Usually the compiler might make them the same instruction with optimization.
>>the following three loops have essentially the same behavior
Just thought I would point this out, in the while loop, long as "//do something" does
not contain a continue or a break statement, its essentially the same, or else there could be a infinite loop or other bugs.
Cut down on the wacky backy kiddo.
Yes I will. Pray for me please.
There is another swap function/. It swaps the two variables. So now its up to you to use that to swap variables around in your vector.
>>Could I put a for loop inside an initializer list somehow
Just to add a little more,
Yea king of, you can do something like this :
struct Foo{
int i;
Foo() : i( bar() );
};
and inside the bar function, there could be a loop or whatever a regular function could have.
>>Also, I often see underscores or something like that
It is just preference, but note that any variable starting with 2 underscores are reserved, and any variable starting with 1 underscore followed by a capital letter are reserved.
Lots of people all over the world write c/c++ programs in languages other than English. However, the c/c++ keywords are all in English. I haven't seen another compiler that use non-English keywords, but that doesn't mean there aren't any.
Oh, I thought he was asking to output to the console in a different language than English.
>>what is the best program that can write C++ more easily?
Best is subjective, but I suggest visual studio, or even Eclipse.
>>2.Can you output C++ in different language beside English ?
I think the farthest you can go with C++ is wide characters, which does not contain any other language letters.
>>4.do you know some useful website for C++ because i have exam next month.
This is a good place to start.
>>5.If you have some CODE about C++ please send me to my email.
If YOU have some code about C++ for which confuses you, then post here at www.daniweb.com, in the C++ section.
Sure here is a skeleton to get you started :
struct Foo{
int x, y;
}
bool operator < (const Foo& lhs, const Foo& rhs){
return /* some boolean expression */
}
Note that you can do what I did there( not make operator< a member function) because
all the members in the struct are public. If not then you would have to include the
boolean operator< as a member function.
I'm sorry, I seriously have to stop posting when I'm not in a normal state of mind.
Please forgive me.
Polymorphism and Inheritance.
It seems as if you are thinking structs in terms of C and not C++. In C++
you can do anything with structs that you can do with classes. The only difference
besides the keywords are that structs have public identifier by default, whereas classes
have private identifiers as default.
Just post random stuff here, anything you want. Say whatever you like. For example,
anyone here have a facebook?
>>how to do the break?
Whats that? Some kind of new dance?
I think this is a good design for you :
#include <iostream>
using namespace std;
struct Base{
int a,b;
Base(int a = 0, int b = 0) : a(a), b(b) {}
virtual int calculate()const{
if(!validatePreCondition()) return -1;
int res = compute();
if(!validatePostCondition()) return -1;
return res;
}
private:
virtual int compute()const = 0;
virtual bool validatePreCondition()const{
return true;
}
virtual bool validatePostCondition()const{
return true;
}
};
struct Derived : Base{
public:
Derived(int a = 0, int b = 0)
: Base(a,b){}
private:
int compute()const{
return a * b;
}
bool validatePreCondition()const{
return a > 0 && b > 0;
}
};
int main(){
Derived d(5,3);
cout << d.calculate() << endl; //show 15
Derived e(0,0);
cout << e.calculate() << endl; //shows -1
}
If a user wants to derive form the Base class, then all he needs to do is define
the function calculate(), and he can add his own pre/post condition. This makes it
much more versatile. The user can create his own pre and post condition if he wishes,
or just create the compute function and use the default pre/post condition that always returns true.
I'm not sure if this is a known pattern or not, but I use it when I need to.
>>Structs are simpler. Structs are old. Structs are not as powerful
May I ask why you think structs are not as powerful as classes in C++?
>>if(isphone=true)
You are setting isphone to true in that loop, instead of testing it. You need to use the binary boolean operator :
if(isphone == true );
in fact, you can even do this :
if(isphone){
}
And for those errors, you named the boolean variable the same as your function name.
Also you are using numbers as if it were a string?
Here is your function without the errors*( not tested )
template<typename BeginItr, typename Fn1>
bool checkIf(BeginItr start, BeginItr end,const Fn1& f){
while(start != end){
if(!f(*start)) return false;
++start;
}
return true;
}
bool hasAllDigits(const std::string& num){
return checkIf(num.begin(),num.end(),isdigit);
}
bool isValidPhoneNumber(const std::string& num){
return num.size() >= 9 && hasAllDigits(num);
}
Its called a Singleton_pattern
EDIT: oops, should have checked to see if sfuo had the same link or not, sorry.
I think you are getting confused. Think of the Nested class as a class of its own. The
only difference is its scope. You can only access it from the outer class. The nested
class has no association with the parent class, besides the scope resolution.
What you are doing is creating a instance of Nested class in the Wrapper class.
Therefore every different instance of wrapper will have different instance of Nested.
You can think of the ternary operator as this :
if( condition )
return firstArgument;
else return secondArgument;
//which is equivalent to this :
condition ? firstArgument : secondArgument;
So when you do something like this :
var arg = condition ? firstArgument : secondArgument;
it basically reads as, the variable 'arg' equals to the value returned by the
ternary argument. If condition is true, then the value of the ternary operator is firstARgument, else the value of the ternary operator is the secondArgument.
Its basically what Fbody said above but more generalized.
So do you want to load .bmp or .jpeg? Wiki has a good description of reading in .bmp and .jpeg. All you need to do is follow the psuedo code.
Just do something like this :
1 : open file to read
2 : open file to write
3 : create a counter variable starting at 1
4 : get user's input
5 : write to file the value of counter variable
6 : write to file the value of the user's input
7 : write to file a newline character
8 : increment the counter variable
9 : repeat 4-8 until done
Much easier way :
string seq = "1 0 1 0 1";
for i = 0 to N
print seq;
First :
template<class P>
P add(P a, P b){
P result;
result = a + b;
return result;
}
is simply :
template<class P>
P add(P a, P b){
return a + b;
}
second, what are you expecting when adding chars? Do you expect M + U to equal "MU"?
If so then consider using string as a type instead of char.
@sundip: not a good advice, since now instead of adding chars, he will be trying to
add char pointers, literally! and not its values.
So for this to work, he has to specialize his add function. So rather than complicate things, just use std::string.
Sure here it is :
#include <iostream>
#include <cmath>
using namespace std;
int main(){
cout << "Please fail me because I asked for this code at www.daniweb.com\n";
cout << "And by the way, the cosine of 45 degrees is : " << cos(45 * 180.0/3.14) << endl;
}
>>ofstream dtfile(""nop"", ios::app);
ofstream dtfile(nop.c_str(), ios::app);
No there is no need for a 3d array. You need to use structures. Here is some things to get you going :
struct Item{
string day;
string time;
int count;
}
std::istream& operator >>(istream& stream, Item& item){
//file format is always : "day - time - count"
//so we read in the day, then dump the '-'. Then read in time and dump the '-'....
char temp = 0;
return stream >> item.day >> temp >> item.time >> >> temp >> item.count;
}
bool sortByDayTimeCount(const Item& lhs, const Item& rhs){
if(lhs.day != rhs.day) return lhs.day < rhs.day; //sort by day first
else if(lhs.time != rhs.time) return lhs.time < rhs.time; //if same day sort by time
else return lhs.cout < rhs.count; //else sort by count
}
int main(){
std::vector<Item> data;
istream file("data.txt");
Item item;
while(file >> item){
data.push_back(item);
}
std::sort(data.begin(),data.end(),sortByDatTimeCount);
for(int i = 0; i != data.size(); ++i){
cout << data.day << " - " << data.time << " - " << data.count << endl;
}
}
Ughhh, why are you using pointers? None of that is necessary. None of it!
Look at your CQuaternion* operator*(CQuaternion& param), it returns a pointer
to CQuaternion, but look at what you are returning in that function, return *temp .
Whats even worse is that this code :
CQuaternion* temp;
temp->w = (this->w)*param.w - (this->x)*param.x - (this->y)*param.y - (this->z)*param.z;
temp->x = (this->w)*param.x + (this->x)*param.w + (this->y)*param.z - (this->z)*param.y;
temp->y = (this->w)*param.y - (this->x)*param.z + (this->y)*param.w + (this->z)*param.x;
temp->z = (this->w)*param.z + (this->x)*param.y - (this->y)*param.x + (this->z)*param.w;
is very wrong because you never allocate space for temp. Because its a pointer,
you need to allocate space for it via new operator. But you use it by setting its
x,y,z values. Thats an undefined behavior.
And the original error you are getting is because you are trying to multiply a pointer against a pointer. Specifically in this
code (this->w)*param.w . That basically says this :
int *x = new int(0);
int *y = new int (1);
int value = x * y; //not valid since x and y are pointers
//what you are looking for
int value2 = *x * *y; //you need to deference the pointer
I suggest you to remove all that pointer. In fact your CQuaternion should look something like this :
class CQuaternion{
// Constructors
CQuaternion(double w = 0,double x = 0,double y = 0,double z = 0);
CQuaternion operator*(const CQuaternion&) const;
CQuaternion conjugate()const; …
If you are trying to erase all contents from the beginning of input until the index
j, then do this:
input.erase(input.begin(), input.begin() + j)
Do this instead :
if(input[i] == "@") //notice the double quotes
{
//...
}