Narue 5,707 Bad Cop Team Colleague
template<typename T>
LinkedQueue& LinkedQueue::operator=(const LinkedQueue& queue)
{
	ll = queue.ll;
	return *this;
}

You need to be more careful about specifying template parameters:

template<typename T>
LinkedQueue<T>& LinkedQueue<T>::operator=(const LinkedQueue<T>& queue)
{
	ll = queue.ll;
	return *this;
}
chunalt787 commented: thanks +1
Narue 5,707 Bad Cop Team Colleague

>Is there a better way?
Yes, design the class hierarchy such that you don't need to know the dynamic type of the object. Perhaps some form of strategy pattern would clean up that selection code.

Alex Edwards commented: Definitely the easiest way to fix the problem! =) +4
Narue 5,707 Bad Cop Team Colleague

>aside from that i am not that proficient in c, i'm more into java
Last I checked, homework assignments were meant to help you learn the subject matter. Thus, claiming that you aren't proficient isn't exactly a good reason not to try.

Narue 5,707 Bad Cop Team Colleague

>If you found it, can you mark this thread as solved?
No pressure though, ai (DO IT! DO IT NOW!!!!!). ;)

John A commented: It's always good to make new members feel at home :) +17
Narue 5,707 Bad Cop Team Colleague

>as for cin.ignore() I have to disagree, I'm using linux and it is neccesary for me to include it.
I reject your disagreement. Most likely you think it's necessary because you've misunderstood the solution to another problem unrelated to what you're actually doing.

Here's how it works. At program startup the standard input stream is pristine; there are no characters present, so calling cin.ignore will block and ignore a single character. Then getline will be called and read any subsequent characters, also blocking if necessary:

#include <iostream>
#include <string>

int main()
{
  std::string line;

  std::cin.ignore();
  getline ( std::cin, line );

  std::cout<<'>'<< line <<"<\n";
}

If you type "testing", the output will be ">esting<". The first character will always be extracted and thrown away, period. Further, because the stream is empty when the program starts, there's no requirement that you ignore the first character unless your program's logic depends on it for some reason (which it doesn't in this case).

>perhaps you should have asked considered the fact that we all use different compilers
What I've described is standard C++ behavior. Yes, we all use different compilers (I use several all by myself), but unless yours is obscure and very broken, it will conform to the standard behavior.

Dave Sinkula commented: :) +17
Narue 5,707 Bad Cop Team Colleague

When you use an array name, it's converted to a pointer to the first element. That's why this works:

int arr[10];
int *p = arr;

By a rights and purposes, an array shouldn't be compatible with a pointer and the assignment should fail. But because arr is converted to a pointer to int before the assignment, it works like this:

int arr[10];
int *p = (int*)&arr[0];

This conversion only applies to the first dimension, so even though you might expect the following to be valid, it's not:

int arr[10][10];
int **p = arr;

The rule is the same: when you use arr, it becomes a pointer to the first element. However, because the rule isn't applied recursively, what you get is a pointer to an array of 10 int, not a pointer to a pointer to int. This is the correct typing:

int arr[10][10];
int (*p)[10] = arr;

// Likewise with further dimensions
int arr2[10][10][10];
int (*p2)[10][10] = arr2;
stilllearning commented: thanks , this was really insightful ! +2
Narue 5,707 Bad Cop Team Colleague

>I would be reluctant to call someone who has written an 800 page reference book 'clueless'!
You might, but I know enough about C to know that the majority of Herbie's books are flat out wrong. He's a good writer to be sure, but a good writer or a good teacher does not equate to a good programmer. My opinion isn't isolated either. When the hacker (that's expert programmers, not people who break into computers) community coins a disparaging slang word in your honor, it's fair to say that you've become infamous.

>I'm sorry if you couldn't understand my reasoning.
I understand your reasoning, but in reality it doesn't apply to the problem you're having.

>so why doesn't the ReadPeriph macro do the same?
Because it does something different. While you may not agree, there's a significant difference between the replacement text of an object-like macro and the argument list of a function-like macro. Different things, different rules.

>I thought this reasoning would be equally obvious.
Nope, I really was baffled by what you were trying to prove with that particular example.

>clearly confirms that it has interpretted SWS as a single variable instead
>of expanding its macro definition of representing three parameters
This is correct.

>so it obviously interprets SWS and its expanded definition of three parameters
This is also correct, but you've stated an obvious truth that has no bearing at all on your …

Dave Sinkula commented: I should drop by the programming forums if you're back in skewering mode. :icon_razz: +17
Narue 5,707 Bad Cop Team Colleague

>I am elated, exhilarated, jubilant, overjoyed, ecstatic and happy!
Well, congratulations. But keep in mind that it isn't how many posts you have, rather what you've done with your posts. For example, I respect Ancient Dragon far far more than, say, christina>you because his posts are focused on helping people while hers are yapping and playing posting games. Both have a respectable post count, but AD has used his posts more productively, in my opinion.

William Hemsworth commented: Very true :] +4
Narue 5,707 Bad Cop Team Colleague

>Found this thread when googling getch, and I had to respond.
I recommend you resist that temptation next time. Posers should know their limits.

>The function you're discussing is NOT a "compiler extension". It's a library function.
If you want to split hairs with terminology, it's a library extension. But whatever you call it, the result is the same: the function is not portable. Calling it a compiler extension is more productive as most beginners can't differentiate between the compiler proper and the libraries. If I say it's a library extension, that will encourage more questions like "I want to use graphics.h with <a compiler it wasn't designed for>".

>The C++ Standard Library is not C++!
That's not quite true. C++ is defined by the C++ standard, and you'll find sections on the standard library in that document. If a compiler package doesn't include the standard library, it doesn't conform to standard C++.

>You can use any library function with any compiler, as long
>as you compile the library source using your compiler.
Perhaps you should try to understand what you're talking about before being a jerk about it. The vendor-provided libraries for a compiler are already compiled. Sometimes vendors provide source code for the libraries, sometimes not. This results in two problems, which are more pronounced in non-portable functions like getch:

1) If you have the source code, chances are extremely good that it uses features, libraries, or APIs that …

Salem commented: Eloquent as ever :) +22
Narue 5,707 Bad Cop Team Colleague

>How do you find out if ThingType thing is in the list?
Loop through all of the nodes and stop when you have a match. It's a basic linear search:

bool TheList::search ( ThingType thing )
{
  Node *it = listPtr;

  // Assuming your list is terminated with a null pointer
  while ( it != 0 ) {
    if ( it->thing == thing )
      break;

    it = it->next;
  }

  return it != 0;
}
Narue 5,707 Bad Cop Team Colleague

>i was wondering if it would be posible to find the
>location at where strtok left like an array index?
Possible, yes. Recommended, hell no. The closest you can get is adding the length of the most recent token to the pointer of the most recent token and subtracting that from a pointer to the beginning of the string. For example:

size_t end = ( category + std::strlen ( category ) + 1 ) - info;

>in my text file there are multiple spaced between each field
Right, you're getting well past the point where strtok is a suitable solution, but you can fix that problem using only the pointers:

char info[] = "        comdey           movie            anger management           12:12:12";

char *genre = std::strtok ( info, " " );
char *category = std::strtok ( 0, " " );
char *name = category + std::strlen ( category ) + 1;

// Skip leading whitespace
while ( std::isspace ( *name ) )
  ++name;

char *length = std::strrchr ( name, ' ' ) + 1;
char *end = length - 1;

// Find the end of the name
while ( std::isspace ( *end ) )
  --end;

// Remove trailing whitespace
end[1] = '\0';
opposition commented: great help, thank you :) +1
Narue 5,707 Bad Cop Team Colleague

Most of your problems can be fixed by using a stack of characters instead of strings:

#include <iostream>
#include <stack>

using namespace std;

int main()
{    
  stack<char> s;
  char a;

  cout << "Enter: " << endl;

  while ( cin.get ( a ) && a != '\n' )
    s.push(a);

  while ( !s.empty() ) {
    cout << s.top();
    s.pop();
  }

  cout<<'\n';
}
Narue 5,707 Bad Cop Team Colleague

strtok isn't that smart. It takes the delimiters you give and breaks up a string based on those delimiters, nothing more. If you want more advanced parsing, you're on your own. If you'd like advice, I'll be happy to help, but you need to be more specific about your needs. It's trivial to handle the exact case you've requested, but if you want the program to recognize which tokens to keep attached, the logic might get tricky.

Alex Edwards commented: Couldn't agree more! =) +4
Narue 5,707 Bad Cop Team Colleague

>If you want to use modulo without floating points try (int)myFloat % (int)myOtherFloat
Brilliant, Holmes. Now show me how your idea works when myFloat is 0.5 and myOtherFloat is 0.3.

VernonDozier commented: Good counter-example +7
Narue 5,707 Bad Cop Team Colleague

>It is C program.
No, it's a C++ program. How do I know? Because GCC doesn't compile it and the error sounds very much like an out of order variable declaration, I seriously doubt you're compiling with the "-std=c99" switch that enables mixed declarations. Since it works on Windows, I can only assume that you failed to compile properly as C and those compilers are defaulting to C++.

Prior to C99 (which isn't very well implemented), all variable declarations must be at the beginning of a block. Meaning your if statement at the top of the function is invalid C (prior to C99).

Narue 5,707 Bad Cop Team Colleague

>So there's a size mismatch.
And yet, the error doesn't say size mismatch, it says signed/unsigned mismatch. Your analysis is logical, but incorrect.

>why is it stated signed/unsigned mismatch when all
>variables are unsigned and no overflow is possible?
Because this is a case where the integral promotions can bite you. To summarize, both operands to the < operator are promoted using the integral promotion rules. i remains as is because its conversion rank is greater than int, so it continues to be an unsigned type. However, the result of x * y (unsigned short) has a conversion rank less than int, so that value is promoted to a type of int, which is signed.

[edit: Darnit, I hate getting interrupted while posting]

twomers commented: Interesting. Wasn't aware that conversion rank was involved, though I suppose it makes sense in retrospect. +6
Narue 5,707 Bad Cop Team Colleague

Yes, seeing as how your code is wrong (you try to use a data member as the return type), it clearly shouldn't compile. But returning a pointer to ArmorArray is quite trivial for you (unless I've misjudged your ability):

#include <string>

struct ArmorArray
{
  std::string armorName;
  int armorCheck;
  int maxDext;
  int price;

  ArmorArray *nxtArmor;
};

class Armor
{
private:
  ArmorArray ArmorList[13];
  ArmorArray *p_List;

  int m_SIZEARRAY;

  std::string m_ArmorName;
  std::string m_String;

public:
  Armor();
  ~Armor() {}

  ArmorArray *BuyArmor();
  std::string CreateString(std::string &myString);
  std::string ArmorBought(std::string &bought);
};

ArmorArray *Armor::BuyArmor()
{
  m_ArmorName = CreateString (m_String);

  for (int i = 0; i < m_SIZEARRAY; i++)
  {
    if(!m_ArmorName.compare(ArmorList[i].armorName))
    {
      return &ArmorList[i];
    }
  }

  return 0;
}

At first I thought you meant you wanted to return a pointer to an array and were struggling with the syntax, which is perfectly understandable.

JoBe commented: Thanks for the help, ... again. +4
Narue 5,707 Bad Cop Team Colleague

Sort your vectors before merging.

Narue 5,707 Bad Cop Team Colleague

>Well personally I think its better suited than std::vector
Ignoring that valarray is designed for numeric types, and ignoring that you can't use the majority of operations with valarray on std::string, and ignoring that you've lost nearly all benefits of the standard library by using a bastard child of the standardization process, and ignoring that the standard definition is broken and many implementations of valarray are substandard because nobody cares enough to fix it in light of exression templates, it probably is better suited. But only for your specific example, and only after ignoring numerous rather large turds that you'll end up eating later.

There are certainly cases where valarray is a superior choice, but that's only because the interface is perfectly suited to the problem and a different solution would result in more complex code. However, this is not one of those cases.

William Hemsworth commented: Don't you ever get tired of being right :)?? +3
Narue 5,707 Bad Cop Team Colleague

>I am just interested to know how many people here
>have managed to become good by learning themselves.
I'm largely self-taught. You can decide for yourself if I meet your definition good or not.

>Also would be interesting to know the general perception
>of self-taught programmers by profesionals is?
The best programmers I've met (professional or otherwise) were all self-taught.

>Personally I struggle with a lot of the more technical/subtle details
Everyone struggles with that, especially if the details can't be compared to existing knowledge.

>but the really trick to it is READING!
Read everything you can get your hands on. Books, blogs, forums, code, everything. But more important than reading is practicing and experimenting. Sometimes there's simply no good documentation for what you want to learn and you have to dig into the guts to figure it out. That's how the really good programmers got good. As I lovingly call it, the "Figure it out your damn self!" teaching method.

Alex Edwards commented: I figured you were self-taught =P +4
Narue 5,707 Bad Cop Team Colleague

>#define p printf
This is an extremely bad idea. If your teacher taught it to you, slap him for me.

>clrscr();
This is a bad idea. Not only is it anti-social (by removing the output of other programs when run in a shared console), it unnecessarily destroys the portability of your code.

>while(a>=1)
First, a doesn't have a predictable value. Second, how are you expecting to count from 1 to 100 with that condition?

>for(a>=0) p("%d",a);
I can't begin to guess what you were thinking here.

Here's a tip, and this is what I personally do when writing a new program, write out a bare bones main function with <stdio.h> and then add to it. Here's the bare bones code that I start with:

#include <stdio.h>

int main ( void )
{
  return 0;
}

Now add the parts you need. For example, you know you want to print the sum of 1 to 100, right? So add the framework for doing that:

#include <stdio.h>

int main ( void )
{
  int sum = 0;

  // Sum 1 to 100

  printf ( "The sum is %d\n", sum );

  return 0;
}

The point of this iterative approach is that you can test at every point. You can verify that your program prints the sum (even if it's always zero) at this point. At the previous point you could verify that the program runs and terminates properly. Now for the loop:

Nick Evan commented: great help for this newbie +9
Narue 5,707 Bad Cop Team Colleague

>i was wondering how much i should use classes in C++.
As often as you need them, obviously. In my experience, this question is born of ignorance. You don't understand OOP and classes well enough to know when to use them, so you try to turn it into some kind of nonsensical numbers game. It's not that simple, unfortunately.

Just try to figure out the concepts behind a feature and eventually you'll learn when and where it's best used.

>Should i use it as much as possible?
:icon_rolleyes:

Alex Edwards commented: Although someone harsh, I do agree! =) +4
Narue 5,707 Bad Cop Team Colleague

I'll go out on a limb and guess that you're using Visual C++ 6.0, where your problem is a known bug.

William Hemsworth commented: Good guess :) +3
Alex Edwards commented: From C++ expert to Psychic? Whoo! =P +4
Narue 5,707 Bad Cop Team Colleague

Command line arguments are passed as parameters to main. The first parameter gives you the number of arguments (including the program name) and the second gives you an array of strings containing the actual arguments:

#include <iostream>

int main ( int argc, char *argv[] )
{
  // The first argument is the program name, if available
  if ( argc > 1 ) {
    for ( int i = 1; i < argc; i++ )
      std::cout<< argv[i] <<'\n';
  }
}
Narue 5,707 Bad Cop Team Colleague

>no i cant.
So what you're saying is that you're unwilling or incapable of searching Daniweb, Google, or any book on C. This is a dreadfully simple problem and the question is asked quite frequently.

>can you pls help me?
No, you're beyond help. If you can't be bothered to do simple research, we can't be bothered to spend our valuable time on a lost cause. Come back when you've actually attempted to help yourself first.

Nick Evan commented: yup.. +8
Narue 5,707 Bad Cop Team Colleague

>flush is a function so you need to use () cout.flush()
std::flush is a manipulator, that part was fine.

>Try this macro
That still won't work as the construction is illegal.

>What I'd like is a way to print the information at compile-time.
That brings up the question of where and how you intend to print it. At compile-time you can really only rely on compiler-specific methods for outputting compile-time messages. You can get close with something like this:

#include <iostream>

#define STR(x) #x
#define TOSTRING(x) STR(x)

template <int N>
struct PrintInfo {
  enum { 
#pragma message(TOSTRING(N))
    RESULT = N + PrintInfo<N - 1>::RESULT 
  };
};

template<>
struct PrintInfo<0> {
  enum {
#pragma message("0")
    RESULT = 0
  };
};

int main()
{
  int result = PrintInfo<5>::RESULT;

  std::cout<<"Result: "<< result <<'\n';
}

But, because the preprocessor runs before template instantiation, you'll only see a bunch of N's rather than the actual value of N for each instantiation.

I'm not a template metaprogramming guru, so the only way I can think of to get a good compile-time output of each value of N is to specialize all of the values:

#include <iostream>

template <int N>
struct PrintInfo {
  enum {
    RESULT = N + PrintInfo<N - 1>::RESULT
  };
};

template<>
struct PrintInfo<0> {
  enum {
#pragma message("0")
    RESULT = 0
  };
};

template<>
struct PrintInfo<1> {
  enum {
#pragma message("1")
    RESULT = 1
  };
};

template<>
struct PrintInfo<2> {
  enum {
#pragma message("2")
    RESULT …
Alex Edwards commented: Simply amazing... =) +4
Narue 5,707 Bad Cop Team Colleague

>I know it's good programming practice to make
>accessor's const. But does it impact speed.
It can, but usually nowhere close to as much as many people believe. const is more for your benefit because it helps make your code easier to work with by adding compile-time invariants.

>Will I get any performance gains by using static keywords, where ever it's possible
Possibly, but it really depends on what you're doing. For example, let's say you have an array of large objects that won't fit in a single cache line. Hoisting some of the data members into statics (if possible) could drop the size of each object to the point where the array fits in a cache line and you might see a sudden and significant increase in performance.

>Will I get any performance gains by using const keywords, where ever it's possible
If saying yes will get you to use const more, then yes. :)

>I never use the "smart" stuff, like protected and
>virtual function. Should I start looking into this.
If you don't need it, don't use it. But if you don't understand it, you don't really know if you don't need it.

>According to <snip url> the virtual functions are especially to avoid.
Virtual functions have an overhead that needs to be considered. But that implies a trade-off, not an "avoid this feature" guideline. I highly recommend you take such advice with the context in …

Alex Edwards commented: Very nice post! =) +4
Narue 5,707 Bad Cop Team Colleague

>I ended up having to do some research on why the cast the
>OP mentioned was legal, and I admit I still do not understand.
Put simply, the cast is an "I know what I'm doing" switch that turns off the safety net. In this case, and on the OP's implementation, it happened to work out.

>I did forget that ( Base* ) is a C-style cast and that I
>do not understand the way the compiler interprets it.
The cast says

"Here is an address. Pretend the memory at that address represents this type"

Since Base and Derived don't have any data, there's a very good chance that the object mappings will overlay perfectly, and accessing d's virtual pointer through a pointer to Base will produce the expected behavior. But let's pretend that Base and Derived have data:

#include <iostream>

class Base {
  const char *p;
public:
  virtual void foo() { std::cout<<"Base\n"; }
};

class Derived: private Base {
  const char *q;

  virtual void foo() { std::cout<<"Derived\n"; }
};

int main()
{
  Derived d;
  Base *p = (Base*)&d;

  p->foo();
}

For the sake of argument, assume that this is how an object of Base is represented internally:

Base::{ vptr | p }

And an object of Derived is represented like so:

Derived::{ Base::{ vptr | p } | q }

It's fair to say the cast will work, and the result will be polymorphic because taking memory originally mapped …

Alex Edwards commented: Thanks for a very detailed explanation on data mappings within objects, Professor =) +3
Narue 5,707 Bad Cop Team Colleague

>Hello guys this is my code.
It's not often that looking at code can leave me speechless.

>Can anyone help me please???
Sure. Let's start by looking at the fatal errors:

>char str[] = { 0 };
As much as many C programmers would love for this to declare a string of unlimited characters, it doesn't. It only allocates one character to the array, effectively giving you either a perpetually empty string (because a null character is required), or a glorified char variable.

>int* cVec = (int*)malloc ( alloc );
You strike me as a C++ programmer who's used to new[] for dynamically allocating arrays. malloc only accepts a byte count, not an item count, which means that on a system with four byte integers you're three bytes short on every item. This causes you to overrun the memory, which corrupts the memory manager, which nearly always results in free choking.

Those are your two fatal errors. They're extremely likely to result in a runtime crash. You also have a portability issues:

>unsigned int alloc = strlen ( value ) + 1;
strlen is declared in <string.h>, yet you don't include that header.

>//works in windows but not on linux
>//cVec[ i ] = int(value[ i ]);
Then you're compiling as C++ in Windows but not in Linux. This cast style is not supported by C. Also note that comments beginning with // are not supported except …

Salem commented: Always a breath of fresh air through mouldy code :) +20
Narue 5,707 Bad Cop Team Colleague

>So is the conversion operator not considered overloading the () operator whereas the
>function call operator is considered overloading the () operator, both are considered
>overloading the () operator, or neither are considered overloading the () operator?
The function call operator and operator() are the same thing. Here's how you can break it down, and it depends on what goes after the operator keyword:

T operator() ( ... )
{
  ...
}

This is overloading the () operator because the operator you want to overload follows the operator keyword (operator()). Notice the seemingly redundant parameter lists, which is a good sign that the () operator is being overloaded.

operator T()
{
  ...
}

This is overloading the implicit conversion operator to type T because the type T follows the operator keyword (operator T). A space is required between the two so that the construct isn't treated as an identifier. The () in that is the parameter list, not the operator to overload.

Your book is correct, but it sounds like it's trying to be too clever in the explanation and causing confusion.

Alex Edwards commented: Wow I honestly was unaware of the conversion overload O_O - whoo! Thank you! =) +3
Narue 5,707 Bad Cop Team Colleague

As I understand the issue, Dani isn't against an automated solution as long as it's generalized. Every time we bring up the issue, she asks us for a good way to handle checking for code tags with every language that Daniweb has a forum for. A good suggestion has yet to be made, so the issue still stands.

>In the c++/c section 'someone' could add a piece
>of PHP code that checks if the post contains main(
And if the post is a snippet without main? A good test is for an opening brace. If the text contains an opening brace, it's a pretty good assumption that the text is code in the C++, C, Java, and C# forums. However, that approach doesn't work well for pretty much any of the other forums, so it fails the generality test.

The only other option is to be excessively strict about code tags (ie. warn, infract, and ban with extreme prejudice), and that's counter-productive if the goal is keeping people around. :icon_rolleyes:

Now for the original request in this thread:

>Remove all mention of code tags from the site
That's a stupid idea, it's easy to figure out why, and the extremity of the suggestion leads me to believe that you're simply being melodramatic.

Removing all mention of code tags (ie. instructions and reminders) would destroy any positive effect that they have. It's silly to believe that the instructions and reminders are 100% ineffective, …

jasimp commented: Well said +8
Narue 5,707 Bad Cop Team Colleague

>I do not know if my code will be portable when I start learning it.
It won't be. Assembly languages are only portable to the processor family (and depending on the features you use, the family subset) they're implemented for.

>Do other Assembly languages conform to the same standards
The core concepts are the same across the board, and that's what you should be trying to learn. Don't focus so much on the difference in syntax because syntax is easy to learn. The hard part is learning how to program at such a low level.

>or is the Syntax incredibly different?
It depends. The difference between NASM and FASM is slight, the difference between FASM and GAS takes a bit of getting used to, and the difference between GAS and something like Terse is staggering. The most widely used assemblers implement similar enough syntax such that moving between them is relatively painless.

>Book recommendations would be great!
Since you're using HLA, The Art of Assembly by Randall Hyde would be helpful for the details of the language as well as the concepts of programming in assembly.

Salem commented: Nicely summed up. +19
Alex Edwards commented: Thanks again Professor =) +2
Narue 5,707 Bad Cop Team Colleague

>>It seems like quite a few people here jump to conclusions that people are looking for homework help.
Since we're quoting ourselves now:

We call it like we see it.

First and foremost, we're all human (except for Salem, who's a C bot). The lack of psychic abilities means we don't know if J. Random Newbie is just having trouble getting his message across, or if he's out to get freebies from nice people so he can pass his class. Because handouts can be so damaging to new programmers, we err on the side of caution and assume that if it looks like homework, it is homework. Very simple.

Nick Evan commented: Agreed on all points (I always knew that Salem was a bot) +8
Narue 5,707 Bad Cop Team Colleague

>So obviously I am missing a fundamental part of the logical not operator.
Let's break it down, starting with the if statement:

if ( ... ) {
  ...
}

If the condition is true, execute the block. Simple, right? Now let's add a boolean test:

if ( x < y ) {
  ...
}

If the result of x < y is true, execute the block. Or in more typical terms, if x < y, execute the block. Still simple, no? What about if we put the result of that boolean test in a boolean variable?

bool test = x < y;

if ( test ) {
  ...
}

If the condition evaluates to true, execute the block. The condition is an expression containing only a boolean variable whose value is the result of the test x < y. The current value of the variable acts as the condition. If the variable is true (ie. x < y), the block will be executed, otherwise it won't. Still simple, right? Now let's start negating:

bool test = x < y;

if ( !test ) {
  ...
}

If the condition evaluates to true, execute the block. The condition is still an expression containing only a boolean variable whose value is the result of the test x < y. But now we've negated that value, so if x < y, the block won't be executed because x < y is true, and negated it becomes false. In …

Vallnerik25 commented: Awesome help, good answers, got to the root of my problem with excellent examples. +1
Salem commented: Indeed it is +19
Narue 5,707 Bad Cop Team Colleague

You formed the string incorrectly ItemFile.open((string)(ItemID+".asw").c_str());

The result of operator+ for std::string is always going to be a new std::string of the same type, so your cast is redundant. This is cleaner:

ItemFile.open((ItemID + ".asw").c_str());
Alex Edwards commented: Zing! +1
Narue 5,707 Bad Cop Team Colleague

>So, what is the difference between NULL pointers and bad pointers
Null pointers have a predictable value while bad pointers do not.

>why do the delete statements fail with the bad pointers?
"Bad pointers" happen when you fail to initialize a pointer, manage to corrupt your memory, or try to free a pointer more than once. Step through your code and see if you can find where the change happens.

Narue 5,707 Bad Cop Team Colleague

>C++ string classes always have string handling/parsing routines similiar to
>those found in BASIC dialect languages that make this sort of work pretty easy.
First, this is the C forum, not the C++ forum. Second, much of C++'s string functionality is available in the form of C functions if you know where to look. Finally, even C++ sucks much ass when it comes to string handling.

Dave Sinkula commented: That last sentence was brilliantly succinct. :icon_razz: +15
Narue 5,707 Bad Cop Team Colleague

To pack? Are you going on a trip? :icon_rolleyes:

>for sure i want to knw C++ and JAVA. But i dnt knw the third!
If you want to go the practical route, select a language you're likely to use. Perl and Python are both good options. If you intend to do web programming then PHP would be a good idea, and depending on what systems you want to specialize in, one of the .NET languages could help.

If you want to push your limits as a programmer, select a language that's fundamentally different than C++ and Java, such as one of the LISP variants, Haskell, or assembly.

Alex Edwards commented: Mean, but funny =P +1
Narue 5,707 Bad Cop Team Colleague

Sorry slick, you came here asking for us to take time out of our lives to hand you answers on a silver platter because you're too lazy to search google for 5 whole seconds. That's made painfully clear with the following incredibly arrogant statement:

Why would I go into a C++ reference and go looking for the command when someone like you could clearly help me quicker

We're not your personal slaves, and after this display of the very attitude that we abhor the most, I recommend you leave Daniweb or start a new account because you're not likely to get any help in the future.

Salem commented: Succinct and to the point as ever. +18
Narue 5,707 Bad Cop Team Colleague

I meant, you can have more than one linked list:

node *it1 = head1;
node *it2 = head2;

while ( it1 != 0 && it2 != 0 ) {
  if ( it1->data != it2->data )
    break;
}

if ( it1 == 0 && it2 == 0 )
  cout<<"Equal";
Q8iEnG commented: You saved me :D +1
Narue 5,707 Bad Cop Team Colleague

>Is there anyway to make %s ignore whitespace?
No, but you can use a scanset to get a little more control. For example, to read an entire line with fscanf you could do this:

char buffer[100];

fscanf ( file, "%99[^\n]", buffer );

However, in your case, selecting which strings go where is a little more complicated. You'd be better off reading an entire line and then parsing it with custom logic.

Crushyerbones commented: Thanks +1
Narue 5,707 Bad Cop Team Colleague

>I am wondering how one would append additional memory
>to the end of a pointer that already has memory allocated?
Assuming one can't use a container class that handles memory for you, realloc doesn't have a C++ alternative, so you're stuck doing it manually. Here are the steps:

1) Allocate a new block with the larger (or smaller) size.
2) Copy the data you want to keep into the new block.
3) Update any aliases you have pointing to the old block to the new block.
4) Release the memory for the old block.

The code might look like this:

#include <algorithm>
#include <cstddef>
#include <iostream>

namespace JSW {
  template <typename T>
  T *realloc ( T *p, std::size_t old_size, std::size_t new_size )
  {
    T *mem = new T[new_size];
    std::size_t n = ( new_size > old_size ) ? old_size : new_size;

    std::copy ( p, p + n, mem );
    delete[] p;

    return mem;
  }
}

int main()
{
  using namespace std;

  int *p = new int[5];

  fill_n ( p, 5, 12 );
  copy ( p, p + 5, ostream_iterator<int> ( cout, " " ) );
  cout<<'\n';

  p = JSW::realloc ( p, 5, 10 );

  fill_n ( p + 5, 5, 21 );
  copy ( p, p + 10, ostream_iterator<int> ( cout, " " ) );
  cout<<'\n';

  delete[] p;
}
Alex Edwards commented: Thank you Narue +1
Narue 5,707 Bad Cop Team Colleague

>C2679: binary '>>' : no operator defined which takes
>a right-hand operand of type 'class std::basic_string
You forgot to include the <string> header.

Q8iEnG commented: Thanks a lot :) +1
Narue 5,707 Bad Cop Team Colleague

>Narue could you elaborate more on this...
People usually have an easier time understanding the rough idea of memory when I explain it using assembly. When a "function" is called, local variables are typically allocated by adjusting the stack pointer to make a big enough gap to hold values for all of the variables:

function:
  add sp, localsize ; Make a hole

  ; Use the locals

  sub sp, localsize ; Close the hole
  ret

That's the general idea behind figuring that the loop doesn't actually reallocate memory with each iteration. In that case, assuming that const_iterator is an class type rather than a built-in type, you can make the examples more accurate like so:

std::vector<int>::const_iterator pos;
for (int i = 0; i < N; i++) {
  pos = myvec.begin();
  // do something with pos
}
{
  std::vector<int>::const_iterator pos;
  for (int i = 0; i < N; i++) {
    pos.const_iterator ( myvec.begin() );
    // do something with pos
    pos.~const_iterator();
  }
}

That seems like a big difference until you consider that the temporaries for myvec.begin() are probably going to be handled identically and that copy construction and assignment are similar enough not to be significantly different in their performance characteristics. Thus the only real difference is that the destructor is called for pos on every iteration in the second example. Unless the destructor is a heavy hitter when it comes to performance (note that the memory isn't being released at this point), the two examples won't much …

Dave Sinkula commented: When's the book coming out? :icon_razz: +15
titaniumdecoy commented: Interesting analysis. +2
n.aggel commented: Thanks for the insight! :) +2
Narue 5,707 Bad Cop Team Colleague

>I understand all the given examples
Really? I still don't understand how some of those examples are expected to work, they're so buggy and poorly written. :icon_rolleyes:

>but the exercises seem impossible
You're pretty much expected to be a graduate student taking higher mathematics courses to do those exercises. Don't worry about them, instead focus on the questions that have you writing code rather than proofs.

>anyone knows a good math book i could use to "get it all"
Look for books on discrete mathematics. That should cover most everything you need for algorithm analysis.

gregorynoob commented: totally, i mean totally made my day... he deserves the rep!!! +1
Narue 5,707 Bad Cop Team Colleague

>/* I dont think my main should return an Integer*/
It doesn't matter what you think. You still have to follow the rules. If you don't like it, go to C99 or C++ where 0 is returned automagically. And if you use C99, be sure to tell us so you don't get blasted for failing to return a value[1].

>I think i am right in this case.
I know you're not.

>But if we dont have to use it , we should make our life simple in terms of compiling.
That's the thing, you do have to use it unless your compiler offers an alternative. If your compiler doesn't offer an alternative, the behavior is undefined. You can't win this battle because nobody who's qualified to have an opinion on the matter will agree that saving a trivial line of code is worth undefined behavior.

>Some material to have a look at:
I've read it, but thanks anyway.

>So i agree with you , that i should use int main() , but a small program
>like printing ASCII and integer doesnot need that much of attention. :)
Rationalize it however you like, but I won't trust your code, and I'll encourage other people not to trust your code, because if you're that sloppy with a small program, who knows what kind of crap you write in larger programs.

[1] Of course, you'll probably still get blasted by the people …

jephthah commented: that's gonna leave a mark. +4
Narue 5,707 Bad Cop Team Colleague

>I don't know enough about C++ or Java to really understand an
>appropriate situation of why one would use one over the other
C++ is well suited for back-end stuff, Java handles everything else. By "back-end stuff" I mean things like the JVM itself.

>I just talked with an individual who claimed that Java is 70% of the programming industry.
Did you laugh at his joke? :)

>Lots of companies that rely on programs to run their business are switching to Java.
Lots of companies that rely on programs to run their business are switching to .NET too. And the point is what, exactly?

>Also he claimed that Java was initially meant to deal with hardware.
It doesn't matter what it was initially meant to do. What matters is where Java fits in the here and now.

>In all of your job-searches, were you more often asked
>if you could additionally program in Java? Or was it C++ ?
It depends on the job. I was a Java programmer briefly, and they didn't care if I knew C++. Currently I work on C++ compilers, so my Java background isn't nearly as much of a factor.

>How many more jobs are there available between C and Java programmers?
It depends on the field, though I'd wager that you'll have an easier time finding a job writing Java than a job writing C or C++.

Alex Edwards commented: Thank you Professor. +1
Narue 5,707 Bad Cop Team Colleague

You can do it with two stacks or with one. With two stacks you would have a stack of operators (single characters at a minimum, but full strings are more flexible). When you pop an operator off of the stack, use the operator itself to determine how many values to pop off of the other stack (binary operators take two, unary operators take one, etc...).

Or you can store strings in one stack while mixing the values and operators. The values go with an operator, so when you hit an unexpected type, you can perform the operation.

Q8iEnG commented: Thanks for the help :) +1
Narue 5,707 Bad Cop Team Colleague

>char in C/C++ actually is a 8-bits integer ranging from 0 to 255.
While that may be true on your PC, C and C++ don't require char to be an 8-bit type. Further, vanilla char is allowed to be either signed or unsigned (the choice is made by your compiler), in which case even an 8-bit char may not have the range you specified.

invisal commented: thanks +4
Narue 5,707 Bad Cop Team Colleague
if (cin.good())
{
  break;
  cin.sync();
}

The sync call will never be reached in this snippet because break leaves the loop immediately.

>why ??
Because when you type a value that cin doesn't expect (ie. a non-integer character when an integer is expected), cin goes into an error state. When cin is in an error state, all input requests do nothing until you clear the state.

What your first example does (in theory) is clear the state and then discard all of the characters in the stream so that you wipe the slate clean and can try again. The second example tries to discard all of the characters in the stream first, even though the stream is still in an error state and the sync call is effectively a no-op because of it.

I say "in theory" because cin.sync() isn't required to flush the input stream.

Salem commented: Doin' the safety dance! +18