Incidentally, C++ has an STL container called a bitset - it might be better to use that than a vector of int's or bool's or whatever. Bitsets are designed with binary operations in mind :)
stupidenator commented: Bench was a lot of help! +1
Incidentally, C++ has an STL container called a bitset - it might be better to use that than a vector of int's or bool's or whatever. Bitsets are designed with binary operations in mind :)
This sort of boolean arithmetic is probably simplest with a recursive algorithm.
for the integers, a and b..
Take a temporary 'carrier' number which records the result of a AND b
bit-shifted one place left.
if the carrier evaluates to zero, the result of the calculation becomes a XOR b
if the carrier is nonzero (meaning, some bits needed to be carried), call the recursive function using the result, and the carrier.
the STL has built-in functions which will help you with most of that, read up on vectors, and see how some of the overloaded operators for vector work. also, look at the <algorithm> header.
the escape character for a backslash is simply \\ - however, as Ancient Dragon says, CD\\ (or indeed any system() call) is unsafe. IIRC, chdir() is part of windows.h or conio.h depending on your implementation - it's not a standard header, but it's certainly better than system().
yeh it appears to be does it not?
No, it's very wrong. string::find() is a function.. I very much doubt that line is doing what you expect.
Also, "$" is not a char, it's a const char* - double quotes mean a null-terminated string, wheras '$' is a single char. Although it shouldn't affect the find() function, which takes parameters for both types.
try this instead
if(a.find('$'))
Can you provide me with another example working out so that I can use the example question and try get an understanding out of it and attempt on my quesion.
Thanks in advance....
You should really pick up Salem's point about decimal - Just imagine you're going back to infant school maths, where you add numbers using columns:
[Thousands] [Hundreds] [Tens] [Units] . [Tenths] [Hundredths]
eg, the number 194.3 is:
One hundred + Nine tens + Four units + Three tenths
In decimal, we get our column headers by powers of the base number (decimal is base 10)
1 unit * 10^-2 = 0.01 (hundredths)
1 unit * 10^-1 = 0.1 (tenths)
1 unit * 10^0 = 1 (units)
1 unit * 10^1 = 10 (tens)
1 unit * 10^2 = 100 (hundreds)
1 unit * 10^3 = 1000 (thousands)
in Binary, the principle is exactly the same.. except binary is base 2.
1 unit * 2^-2 = 0.25 (quarters)
1 unit * 2^-1 = 0.5 (halves)
1 unit * 2^0 = 1 (units)
1 unit * 2^1 = 2 (twos)
1 unit * 2^2 = 4 (fours)
1 unit * 2^3 = 8 (eights)
So, for the number 1001.0110, we need a table like this
[8] [4] [2] [1] . [0.5] [0.25] [0.125] [.0625]
1 0 0 1 . 0 1 1 0
So, back to infant school maths - here's our calculation
One eight + No fours + No twos + One unit = 9
+
No halves + One quarter + One eighth + No sixteenths = 0.375
result = 9.375
ya that's ok with me, but how do I get a record with the smallest? That's the question that I'm trying to find an answer for.
How would you do it in real terms? Imagine someone calling out bingo numbers, and you're looking out for the smallest.
The first time he calls out a number, you remember that number, because it's the smallest number he's called so far.
Second time, you ask yourself "is this smaller than the smallest number?"
if the answer is yes, you remember that one
if not, you wait for the 3rd number... etc.
I think I've gotten a little bit further, but still have yet to grasp classes, this is what I've got now.
What exactly are you having trouble understanding? Your class looks fine for the most part
void SodaCan::get_volume ()//can volume = piR^2H { volume=((pi*(radius^2))*height); } void SodaCan::get_surface_area ()//can surface area = 2piRH+2piR^2 { surface=((2*pi*radius*height)+(2*pi*(radius^2))); } // the driver: int main() { SodaCan can(10, 5); //height is 10, and radius is 5 cout << can.get_volume() << "\n"; cout << can.get_surface_area() << "\n"; return 0; }
Your problem here is that get_surface_area() and get_volume() functions both have return type void - so passing them to cout won't do much :) Remember that those 2 functions run a calculation and assign them to a variable, they don't output anything.
If you edit those functions so that they return the result of the calculations instead (a double), then you won't need the two values inside your SodaCan class surface and volume.
Hello all,
Thank you ahead of time if anyone answers this.
I am new to c++ and am having some difficulty understanding my assignment.
I wrote some code that does what the teacher has requested but according to her it does not utilize a function. I know that I have to call a function and that the function should not have to have user input to work but I don't really know how to modify my existing code to implement a function.
(I thought I was, as the program does what it is supposed to do, just not the way she wants it to be done.) PLEASE HELP!! HERE IS THE CODE I HAVE
It's a little unclear from your post exactly what you want to do -
If I understand you correctly, your teacher is asking for a function which will take the input as an argument, rather than from the user, something like this..
int reverse(int input)
{
// reversing algorithm here
}
Your SodaCan class needs a constructor to assign something to the private height and radius data members. eg, the line
SodaCan can(10,5);
requires a constructor which looks like
SodaCan::SodaCan(int, int)
Much in the same way that, for an library type, such as std::string you can say
std::string s("Hello");
which will initialise s with the value "Hello" - Of course, the constructor for std::string is well hidden inside the standard library, but there's a constructor somewhere, which may have a signature like
string::string(const char*)
Check out this link for more info :)
C++ FAQ - Constructors
NOPE NOT BROKEN I DONT CARE IF I USE CORRECT GRAMER ONLINE AS LONG AS IT GETS THERE AND THE PEOPLE CAN READ
There's no need to shout either. You might think that spelling & grammar are superfluous online, but if people have to first decypher your message to understand your problem, you will generally get less helpful responses. Its your call.
IT AND AS FOR Ancient Dragon I TOTALLY AGREE WITH YOU BUT WHAT ARE OTHER WAY BETTER BOOKS BECAUSE ALOT OF THE DUMMIES BOOKS SUCK LIKE U SAID OR I MEAN WHAT I INFERED FROM YOUR WRITING
take a look at the book reviews section of http://www.accu.org
There's alot of books out there which are badly written and/or outdated, so check the reviews for books which are marked "highly recommended" or even "recommended". There's a section there containing reviews of beginners' books. I suggest you have a look at You Can Do It by Francis Glassborow, to get you started. the book, which is aimed at complete novices, assumes no programming experience at all. That one is much, much better than the "For Dummies" book IMO.
What kind of partition function are you using? does "G" appear before "F" in the alphabet?
This program works...
I don´t know if it's like this that youi want:
//snip
Most probably not! choose a language, either C or C++, and stick to it.. mixing the two like that is really a very very bad idea.
A margin is just blank space around an object on a page (or a screen). Since your output goes from left to right, the only margin you care about is the left-hand margin... How would you add a margin of, say, 5 spaces to a text document in Windows Notepad..?
>Andy,
>Great Web page, I actually looked at before you even responded.
That's not me or MY website. I just like it cos it's kewl :lol:
You're kidding right? That's an epilleptic's worst nightmare!
All this use of '\0' is very C-like ..There is a much better way using C++ strings (And by the way, ignore the use of <string.h> <iostream.h> and void main() )
C++ strings have a size() function which tells you how many characters are in the string.
#include <iostream>
#include <string>
int main()
{
std::string sentence("hello, I am a string with 7 spaces.");
int spaces=0;
for(int i=0; i!=sentence.size(); ++i)
spaces+=( sentence.at(i)==' ');
std::cout << "number of spaces: " << spaces;
std::cin.get();
return 0;
}
Note - sentence.at(i) is the C++ equivalent of sentence. you can use either form, and your compiler won't complain, but the at() function is automatically range checked.
If you spent the same amount of time doing your own homework as you do with other people's you wouldn't be using void main()
I fixed your post ;)
Why is that?
I think Narue is nitpicking a bit... nevertheless its the right answer according to the text in the post - The OP has probably made a typo (assuming he copied it from a book or sheet).. it took me a few reads to work out what the error was :)
(Compiler error would go something like "dptr: undeclared variable")
Compile this code.. then try changing bits of it... what happens when you modify it to some of the scenarios given in your homework assignment..?
#include <iostream>
using namespace std;
class duck
{
public:
virtual void speak() { cout << "quack"; }
};
class swan : public duck
{
public:
void speak() { cout << "This is a swan"; }
};
class heron : public duck
{
public:
void speak() { cout << "This is a heron"; }
};
int main()
{
duck* myDuck = new swan;
myDuck->speak();
cin.get();
return 0;
}
when you "free" memory, you are deleting the object which "temp" points to, you are not modifying temp itself. What you are left with is a dangling pointer which points to some undefined part of memory, which could contain absolutely anything. you should assign the value of NULL to "temp" after freeing the memory.
Your loop is trying to access outside the range of the array.
Your array is size 5, that means, the elements are indexed by the numbers 0-4... yet your for loop says:
for (j = SIZE; j < i; j++)
You need to loop from j=0 to j<SIZE
also, you might want to check this..
for (cnt = 0; cnt < SIZE; cnt++)
{
if (scanf("%d", &gross[cnt]) == 1)
{
gross[i] = ((gross[cnt] * .09) + 200);
i++;
}
}
Remember that you've initialised i with the value of SIZE... you have the same problem here as above.
(I don't really see why you use the variable 'i' anywhere in your program - you don't actually need it..)
If you're not sure about e() and f(), You probably need to ask a different question... such as "How many methods does an object of class D have?" .. because then the answer is 4. :)
I see, that would make sense I guess...*scratch* Now Im going to have to find some way to initialize them I guess. *sigh* Function calls....unecessary function calls....ugly.
I assume that this is some kind of a lookup table? How about wrapping your map inside a class, and using the constructor to initialise it?
Remember : every time you use the word "new" - make sure you also use the word "delete" (or better still, create a class which handles all the dynamic memory stuff).. at the moment, your program has got memory leaks!
Also, change "void main()" into "int main()" (and, unless you're on an ancient compiler, change <iostream.h> to <iostream> )
if(1<d<b)
What do you intend this bit of code to do? What it is actually doing could be rewritten as ( (1<d) < b)
In other words - the result of 1<d will either be true or false (0 or 1)... this result is then compared with b - probably not exactly what you intended!
Never rely on operator precedence, even if it appears at first to do what you intend. use this instead:
if ( (1<d) && (d<b) )
There may be more errors, but those are all I've found so far.
Do you mean to say that 2 of the derived classes share a member which the 3rd one does not?
If so, you probably need an intermediary derived class, which contains those shared member(s) (either public or protected) - and derive the 2 "related" classes from this intermediary class. eg,
class base;
class intermediary : public base;
class derivedA : private intermediary;
class derivedB : public intermediary;
class derivedC : public base;
Hi, I'm new to this C++ stuff. So if anyone can help that would be nice. I have this program to generate a random number and a the user inputs a number from the keyboard to correctly guess the number that the computer randomly chooses. but the numbers are always changing each time, which makes it hard to correctly guess the correct number. So the question is, is it possible to randomly choose a number without it changing each iteration?
Wrap your code in "Code Tags" - makes it easier for everyone to read. :)
Aside from Clinton's excellent spot, there is a slight flaw in your logic...
//Snipped #include's
int main ( )
{
int guess;
char ans;
srand (time (0));
for (int i = 0; i < 100; i++)
{
So... everything after this curly brace (up til the closing brace) gets repeated 100 times.. including:
int random = rand( );
int num = ((random % 100) + 1);
I suggest putting these 2 lines before your loop starts, then you will only be selecting your random number once.
Also, this kind of "guessing game" would look much cleaner if you could say do....while(guess!=num) instead of for...
It would help if you could paste the exact error(s) - Be aware VC++ 6.0 is out of date, I strongly recommend downloading a newer compiler before you do anything else. There is definitely more than just one error in that code!
It looks to me like you are trying to do too much without understanding what you're doing. Start out simple - try making a small program that just takes user input and displays it on the screen. before you go on, you need to declare and initialise variables properly. You also need to use identifiers without spaces. Once you've got that compiled properly and working, expand the program... Walk before you run ;)
"bool" is short for "boolean" - look it up in any dictionary or computer science website. in C++, bool is a data type for an object which accepts only true and false (or, alternatively, zero for false, and non-zero for true)
if (d <= 31 && d >= 1 && m <= 12 && m >= 1 && y <=2006)
This was the first problem I noticed. Put your individual comparisons inside brackets. Think of each comparison as an individual expression.
if ( (d<=31) && (d>=1) &&
(m<=12) && (m>=1) &&
(y<=2006) )
Personally, I would break this down into 3 seperate checks - this allows you to give more specific information about which part of the date went wrong, eg,
if ( (d<1) && (d>31) )
cout << "ERROR: Out of range for day" << endl;
Generally, your input.txt should go in the same place as your executable. If for some reason, this is causing you problems, or you do not know where the executable is, refer to the complete path of the txt file explicitly, for example, in DOS/Windows, you'd use
ifstream fin ("C:\\MyProgram\\input.txt");
the double-backslash is necessary, since the file location is a string (and '\\' is the escape character for a single backslash)
Hey guys i need to find out how many days there are in a particular month in a particular year.
How can i start building an algorithm like that im having some trouble?
Since there's no relation between the month and the number of days it contains, your best (portable) option is to use a lookup table.
(Or, you could use some non-standard windows function to look it up, but lets go with the portable method for now :) )
std::map<std::string, int> daysInMonth;
daysInMonth["january"] = 31;
daysInMonth["february"] = 28;
//etc
Then, somewhere else in your code, you might have...
std::string myMonth = "january";
int lengthOfMonth = daysInMonth[myMonth];
edit : Oh, of course, this doesn't take leap years into account..
You'll have to make a few ammendments though
Maybe you could change
"C++ is an object-oriented programming language"
to
"C++ is a multi-paradigm language which supports object-oriented programming"
Or am I clutching at straws there? ;)
if they type anything less then 0 or more then 12 its an error
Are you sure about that? What month is zero? ;)
server_crash gave you a good outline for a class, including constructor & destructor.
If you've never created your own data types before, try a simple struct with some data members. In C++ both class and struct are essentially the same thing (the only difference is that class defaults members to private, and struct defaults members to public) You can then add some functions (eg, a "get data" or "set data" function).
// I'm A Noob but I hope this helps ~ any comments are welcome
You really need a new compiler. You're honestly not helping yourself by learning pre-standard C++ (And i'm afraid to say that pasting code like that won't help anyone else either. Even with the conio stuff removed, your code won't compile on some modern implementations).
If you want to stick with Borland, then AFAIK, they have a free version of their CPP-builder available. Otherwise, there are other free compilers available for windows - MS VC++ toolkit 2005, Quincy, MingW... and probably more that I can't think of right now. a google search will turn up a load of results.
I can see how you might have one class and one 'driver' program, but I don't understand why you would want more than one class.
My guess is that he wants one for roman numerals, one for Arabic numerals, etc. Maybe switching between the two using dynamic binding and inheritance.
[Edit: I just realised that by "arabic numerals" he meant "Decimal". However, the program could be converted to one of the greek numeration systems instead for example]
if (roman_num[counter] == 'M') number = 1000; else if (roman_num[counter] == 'D') number = 500; else if (roman_num[counter] == 'C') number = 100; else if (roman_num[counter] == 'L') number = 50; else if (roman_num[counter] == 'X') number = 10; else if (roman_num[counter] == 'V') number = 5; else if (roman_num[counter] == 'I') number = 1; else number = 0;
To make life easier, you could replace all those cumbersome if/else statements with a std::map lookup table, (which could be incorporated to your Roman Numeral class) eg,
std::map<char, int> RomanDigits;
RomanDigits['I'] = 1;
RomanDigits['V'] = 5;
RomanDigits['X'] = 10;
// etc.
You would need an algorithm to handle the case where the input is not a valid roman numeral, for example, a find would return the end of the container if no match for the input is found.
D'oh, I misread the thread - post contents deleted.
we were introduced to classes as well. should I use a class node instead of a struct node?
"struct" and "class" in C++ are actually the same thing with one very subtle difference - "struct" defaults to all members public, "class" defaults to all members private (use the public/private/protected keywords if the visibility of a member needs to be different). Which one you use is up to you, although, typicallylly 'struct' is used for simple data structures containing no functions, overloaded operators, etc.
For a linked list, you are undoubtedly going to be including functions, so 'class' would be the more idiomatic choice - It is considered good style to make your data members private and provide public functions as an interface to access the data.
should the functions to decrement the sodas be part of the data in the node or should it be separate?
As a rule of thumb, put the function to manipulate the data inside the structure in which that data is kept (keeping the data private means that non-member functions can't access it anyway).
do I need two pointers or one to traverse the nodes and find the correct info to be used during use?
Judging by your assignment, you are only going to traverse the list in one direction, so you only need a single pointer to the next element.
Continuing the conversation with myself... :)
Now that I've had some sleep, It's pretty clear that you don't want your operator<<() to be a member function of Stack, because the syntax to pass to cout is completely counter-intuitive, compared with the rest of STL. The "best" way is for you to make operator<<() a non-member function.
Incidentally, and this is a style issue - if you create the operator as a member function, I think you should use operator>>() (I'll explain in a second...)
ostream & Stack::operator>> (ostream &ost)
{
for (int i=0; i<=top; ++i)
{
ost << arr[i] << ' ';
}
return ost;
}
operator<<() is sometimes known as "put to", whereas operator>>() is respectively "get from"
You would be using your operator to "get" the data in arr[] "from" your Stack.
eg,
Stack MyStackObj;
// ..Populate MyStackObj here..
MyStackObj >> cout;
operator<<() is a member function - you can only pass one parameter at a time to your Stack object using operator<<() - eg,
Stack myStackObj;
myStackObj << SomeValueHere;
If you are merely trying to overload operator<<() then it should be a non-member function.
When defined as a member, the object for which it is called is implicitly "this" (Just like any other member function). The same applies for the any other binary operators which you have defined as members of your stack - you only provide one argument because the "Left-Hand-Side" argument of a binary function is implicit.
Also, being a member function, there is no need for the 'friend' keyword.
pls help me to write a program that will input a word or a sentence and display that youve inputted in a reverse form. if the word you entered is the same as the reverse one, "Palindrome" will be displayed. Otherwise,"NOt Palindrome"
2 Ways to do this - Either create a reversed copy of the string, and do a comparison, else use two iterators or placemarkers to compare characters of the string from the outside-in.
Using Microsoft compilers, I am not at all convinced that std::cout is faster than printf(). I have made similar tests in the past on other computers with M$ os and have never seen one where cout is faster than printf(). And I would be supprised if *nix computers was any different.
Although I think the real point here is that it doesn't really matter whether cout is slower than printf. I can think of few situations outside of a programming-for-speed competition where the relatively small speed difference between printf/scanf and iostreams is of greater consequence than the ugly C-style code which results in the use of printf. Especially when considering that the 'advice' has been directed to a forum populated with many learner programmers, students, and C++ beginners.
I can think of a better way. if you wish to calculate the sum of all numbers in a range, the formula is n( (First+Last)/2 )
in your case, the first number is always going to be 2 ... 'n' is the "number of numbers" in the range.. eg, from 2-to-12, n=6 ... or 2-to-100, n=50... or 2-to-10000, n=5000.. (see a pattern there?)
I've been working on this program all day and I'm so lost please help! I need to have a class that uses a 40 element array that has predicate function IsEqual, IsGreaterThan, etc and with member functions input, output, add, subtract. Is there anyway I can make this code smaller?
Try using a vector, or some other STL container instead of arrays
Also - Rather than creating operations such as "add" and "subtract", use operator overloading, so that you may simply use your HugeInteger class in this way:
obj1 + obj2
overloading operators such as operator<() and operator==() will allow you to use the STL predicates, rather than creating your own.
Why should references be used at all?? As we could always use pointers in place of them as if we change the value of the pointer , automatically the value of variable it points to is changed eg. p=&s;*p=7;
I think you almost answered your own question - why use references? Well, because pointer syntax can look ugly. pointers are also error prone. In general, use References whereever you can, only use Pointers when you have to.
Might I have an explination as to whats up with the change, and a point to an online tutorial thats up to date?
The reason for the change is a little long-winded and boring, but it has to do with the fact that up until 1999, C++ was not standardised. When the standardisation came along, the ISO Committee decided that requiring vendors to modify their own versions of iostream.h could potentially break so much legacy code, that the best solution was to allow the vendors to keep their deprecated iostream.h, and add the new, standard one in the form of <iostream>. The same is true for all standard library headers (eg, <string>, <vector>, etc). There is also talk that one day, the older headers ending in ".h" may be completely removed from C++
As for tutorials, be aware that many are of varying quality, and sometimes mix old and new code. Nevertheless, there's alot of information around. My favourite starting point for any subject is Wikipedia, so have a look here: http://en.wikipedia.org/wiki/C_Plus_Plus
The links section in the wiki entry (right at the bottom) has a bunch of tutorials and other useful C++ stuff - plenty to keep you in reading material.
If you can afford it, buy a good quality beginners' C++ book. The ACCU (Association of C and C++ Users) has a reliable book reviews section. ( http://www.accu.org )
If you can't afford a book at the moment, check …
I have no idea what that means. :eek:
caseg is probably from the UK, because "diss" is Brit-slang for "disrespect". :)
Then why don't you suggest another way. :D
How about this? Although it uses equality, which is technically a comparison operator. "Is i1 greater than i2?"
bool greaterThan(const int& i1, const int& i2)
{ return ( ((i2-i1)==abs(i2-i1)) ? false:true ); }
The whole idea of 'for' loops is that you type the code once, and the loop will repeat it. The reason you are getting the same output multiple times is that you have the same 2 lines occurring 20 times.