Narue 5,707 Bad Cop Team Colleague

>It's obvious the fgets i gonna really until '\n' or EOF as per the specification of fgets.
It may be obvious, but it's wrong because fgets is constrained by the size of the buffer you give it. Let's say your buffer is large enough to hold 10 characters and a null character. What happens if the line contains 20 characters?

The specification of fgets says that the buffer will be filled as usual, but because there's no newline, no newline will be stored. This way you can use fgets with multiple calls to read lines that are longer than the size of the buffer simply by checking for the presence of a newline character. If there's a newline, you've found the end of the line. If there's not a newline, you've only read a partial line.

Narue 5,707 Bad Cop Team Colleague

>there is something called internal ,typecasting which will type cast the return type for you
The conventional terminology is "implicit conversion" while casting is another conventional term for explicit conversion.

Narue 5,707 Bad Cop Team Colleague

>you could have a look at a fgets function, which actually reduces few lines of code
Really? Let's look at the original:

do {
  c = fgetc ( file );

  if ( c == '\n' )
    lines ++;
} while ( c != EOF );

Six lines total, five lines with code. Now let's look at the same solution using fgets:

while ( fgets ( buffer, sizeof buffer, file ) ) != NULL ) {
  char *newline = strchr ( buffer, '\n' );

  if ( newline != NULL )
    ++lines;
}

Hmm, six lines total and five lines with code... Sure, you can play formatting tricks to make the code more compact, but the base solution is the same length. Or you can alter the organization of the original and have something more compact than with fgets.:

while ( ( c = fgetc ( file ) ) != EOF ) {
  if ( c == '\n' )
    ++lines;
}

>This is just to give you some more clarity for your code.
That's debatable. Personally I think it's more obvious what the original code is doing.

Narue 5,707 Bad Cop Team Colleague

>Actually, I find just as many people use plain text code tags or try to specify a
>language and get the syntax wrong as people who don't use code tags at all.
Looking at the statistics of cases we moderators deal with on a daily basis, failure to use code tags is vastly more common than failure to use them correctly. I'd say that out of 100 cases where I have to edit a post for code tags, maybe 8 or 9 of those cases involve fixing the tags and the rest involve adding them.

Narue 5,707 Bad Cop Team Colleague

I know that it's easy to misread "Daniweb" as "rent-a-coder", but we don't do that here. If you have a specific problem we can help you, but we won't do your work for you and hand it to you on a silver platter.

Salem commented: + for truth +17
Narue 5,707 Bad Cop Team Colleague

>Are C++ & JAVA the only 2 dominant language in the industry?
Hell no. They're just the most commonly bitched about. ;)

>If yes why not any other language like BASIC.
BASIC itself tends to be restricted to students these days, but variants of Visual Basic are still going strong.

>If no, what are the other languages used?
Some of the more popular/trendy are assembly, C, VB6, VB.NET, C#, Ruby, Haskell, F#, Perl, Python, PHP, Delphi, Javascript, VBA, and about fifty-jillion others that don't come immediately to mind.

Narue 5,707 Bad Cop Team Colleague

>Dev C++ let me skip those for some reason.
Now you know why it's a good idea to test your code with multiple compilers.

Narue 5,707 Bad Cop Team Colleague

>why is referred two times the 'sizeof Msg1' (sizeof Msg1 / sizeof *Msg1) separated by '/' ?
The size of the array in bytes (sizeof Msg1) divided by the size of a single element in bytes (sizeof *Msg1) gives you the number of elements in the array. It's a way of avoiding magic numbers by calculating the number of elements at compile-time.

Narue 5,707 Bad Cop Team Colleague

Hmm, tough cookies. By the time you've instantiated objects, each object has a separate copy of the variables, so you have to update each object separately.

That said, it's possible to update all of the variables at once, but only if they're inherited as static members to class A:

#include <iostream>

class A {
public:
  static int x;
};

int A::x;

class B: public A {};
class C: public A {};

int main()
{
  B b;
  C c;

  b.x = 12345;

  std::cout<< b.x <<'\n';
  std::cout<< c.x <<'\n';
}

However, this also means that every object will always have the same set of values. They can't be independent and simultaneously updated at the same time.

Narue 5,707 Bad Cop Team Colleague

>I did not add break, because it is not a must in switch case.
If you don't break out of a case, you'll continue to execute the cases below it. That's very rarely desired behavior, which is why pretty much every style guideline requires a comment if you really want fallthrough:

switch ( radix ) {
case DECIMAL:
  // FALLTHROUGH
case OCTAL:
  // Do stuff for decimal and octal
  break;
default:
  // Error
  break;
}

Without the break in the octal case, every radix would be treated as an error even after being successfully processed as decimal or octal.

Narue 5,707 Bad Cop Team Colleague

>getline() function is in the library of #incude <conio.h>
Um, no. The getline function (the one that accepts a std::string) is declared in the <string> header.

>but it doesn't come up with the desire output.
Here's a pattern that you'd be wise to learn so you can spot it again:

#include <iostream>
#include <string>

int main()
{
  using namespace std;

  int value;
  string line;

  cout<<"Enter a value: ";
  cin>> value;
  cout<<"Enter a line: ";
  getline ( cin, line );
  cout<<"Value: "<< value 
    <<"\nLine: "<< line <<'\n';
}

Formatted input (cin's >> operator) and unformatted input (getline) don't play well together. The error in this specific pattern is that while cin's >> operator trims leading whitespace, it doesn't trim trailing whitespace, which causes the newline character to be left in the stream for the next input to deal with. However, getline uses a newline character as a delimiter by default, so when it sees that character it terminates immediately. The effect is that the getline call is "skipped".

The fix is to remove the newline character using cin.ignore() , but a lot of people don't want to deal with dirty streams so they'll simply clear out the remaining characters as garbage and leave the stream pristine for the next input:

#include <iostream>
#include <string>
#include <ios>    // For streamsize
#include <limits> // For numeric_limits

int main()
{
  using namespace std;

  int value;
  string line;

  cout<<"Enter a value: ";
  cin>> value;

  // Clear the stream so …
Narue 5,707 Bad Cop Team Colleague

>Switch case is faster if there are more than 2 conditions to be checked
First, you shouldn't use absolute statements like "X is faster than Y", because you'll nearly always be wrong. Second, where did you come up with two conditions? That seems like a very compiler-specific statement to me.

>since it maintains a table of pointers to execute instruction
That's one valid implementation, but it's not required. Even with that implementation, you can't claim a switch to be faster in all cases because in your example var could always be 1 and the first if will run every time, which amounts to the same thing as the table jump in a switch.

Hell, a switch could be orders of magnitude slower than an if chain (or vice versa) if you get unlucky with cache effects. There are so many variables in the performance of a program that it's always better to write your code with clarity in mind and optimize only after profiling shows that there's a bottleneck.

>And also switch case looks good.
Subjective. Not to mention that your example clearly used a style that makes the switch look better. This is more correct (I added breaks to the switch) and more conventional (most people don't indent their else ifs):

switch (var)
{
case 1:
  // do something
  break;
case 2:
  // do something else
  break;
// more cases
}

or 

if ( var == 1 )
{
    // do someting …
Narue 5,707 Bad Cop Team Colleague

>Just curious, if not on heap and stack..where will it be?
String literals could be stored in the static data areas of the executable since they're known and can be completely resolved at compile-time.

>Or else will it cause memory leak if not deleting it explicitly?
Generally, you shouldn't delete something explicitly if you didn't allocate it explicitly.

>I heard heap in c++ lexicon is freestore
It's called a lot of things, but "dynamic storage" is probably closest to the language standard.

Narue 5,707 Bad Cop Team Colleague

>can somebody tell me is there a problem in it ?
Assuming boolean is a typedef, there's nothing syntactically or semantically wrong with that function. Perhaps if you told us what it's supposed to do, we can tell you if it actually does it.

Narue 5,707 Bad Cop Team Colleague

>you delete[] m_Contents; since it was allocated onto the heap not str.
I think it's safe to assume that the point of this constructor is to allocate memory to m_Contents and initialize it. Releasing m_Contents seems kind of counter-productive at this particular point in execution. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

>May I know "Candy" is on heap or stack?
Probably neither, and it doesn't matter as the compiler manages the memory for string literals. Trying to delete memory that you didn't explicitly allocate would be most unwise.

Narue 5,707 Bad Cop Team Colleague

>Is the scope you use supported by c90 or is it a c99 feature?
You're thinking of the mixed declarations feature of C99, which is different. C90 supports declarations at the beginning of any block, not just the beginning of the function, while C99 supports declarations mixed with other statements.

>so would a buffer be if I read the file to a string?
Yes, in that case you have to consider lines that are longer than the string can hold. Just blindly copying characters into the string could overflow the memory, and that's what you need to look for.

Narue 5,707 Bad Cop Team Colleague

>char c;
c should be an int, because that's the type that fgetc returns. Specifically, EOF may not be handled properly and certain values may overflow a char.

You should also limit the scope of your variables as much as possible. I'd write it more like this:

#include <stdio.h>
#include <stdlib.h>

int main ( int argc,char *argv[] )
{
  if ( argc == 2 ) {
    FILE *file = fopen ( argv[1], "r" );

    if ( file != NULL ) {
      int c;
      int lines = 1;

      do {
        c = fgetc ( file );

        if ( c == '\n' )
          lines ++;
      }
      while ( c != EOF );

      printf ( "%s has %d lines\n", argv[1], lines );
    }
    else {
      puts ( "Can't open file" );
      return EXIT_FAILURE;
    }
  }
  else
  {
    puts ( "Only enter one file name" );
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Beyond that it looks like a good start. :)

>I know file and user input can be insecure because of buffer overflows.
Of course, that doesn't apply to your program as you aren't using a buffer. ;)

Narue 5,707 Bad Cop Team Colleague

Have you tried fscanf? :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

>warning: passing arg 1 of `fread' makes pointer from integer without a cast
It's generally a good idea to fix your warnings. In this case, check the documentation on fread and you'll notice that it takes a pointer to void as the first argument, not an int.

Narue 5,707 Bad Cop Team Colleague

>If a gm can close this... That'd be great
We don't close threads when they're solved, but it's possible to flag a thread as solved to notify readers that you got your answer.

Narue 5,707 Bad Cop Team Colleague

Don't use an array. A std::set or std::map seems much better suited to your problem.

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

FYI, the mod team is discussing this and working on a change to the wording of that clause.

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

>So what exactly is the benefit of C++ pointers?
You have much more control with pointers than you do with references. References (in Java at least) are designed to be pointers without the dangerous aspects of pointers, but it's those very dangerous aspects that give pointers incredible power if you know what you're doing.

Narue 5,707 Bad Cop Team Colleague

and it doesnt mention code-tags

Code tags are a feature of Daniweb's forum. You take your code and wrap it in code tags like so when you want to post it here:

(code=cplusplus)
<code from your book here>
(/code)

This preserves the formatting of your code rather than trimming all leading whitespace from it. With the cplusplus attribute, line numbers and color coding are also added. Here's how code looks without code tags:

#include <iostream>

int main()
{
  for ( int i = 0; i < 10; i++ )
    std::cout<<"Hello, world!\n";
}

And here's the same code with code tags:

#include <iostream>

int main()
{
  for ( int i = 0; i < 10; i++ )
    std::cout<<"Hello, world!\n";
}

Notice the difference?

p.s. We give you about 10 posts to learn how to use code tags, then start issuing infractions for each failure to use them. At 2 points per infraction, that means you can get off five posts before you're automatically banned for not following our rules.

Narue 5,707 Bad Cop Team Colleague

Do you know how to multiply two numbers in C? You can multiply a value with itself, and that's all you need to know to find the square and cube of a value.

Narue 5,707 Bad Cop Team Colleague

>i think it needs some formula
Do you even know how to find the square and cube of a number? It's pretty basic arithmetic, and you can use what you learned from my last post to do the output.

Narue 5,707 Bad Cop Team Colleague

>void main()
Use this as a template:

#include <stdio.h>

int main ( void )
{
  /* Your code here */

  return 0;
}

>clrscr();
Unnecessary, anti-social, and you forgot to include <conio.h>.

>getch();
Unnecessary, non-portable (use getchar if you must), and you forgot to include <conio.h>.

>but i need to make it like this:
How about something like this:

for ( n = 1; n < 10; n += 2 )
  printf ( "%d\t%d\n", n, n + 1 );
Narue 5,707 Bad Cop Team Colleague

>Is there a difference, in terms of performance, between the two loops below?
It depends on your compiler. There are tons of factors that come into play, such as how your compiler manages stack space, whether the underlying type of const_iterator is a simple pointer or an object, how temporary objects are managed, whether object creation/destruction outweighs copy construction/assignment or the creation/destruction is a bottleneck, etc...

The best answer is that if it matters you'll notice a problem during performance profiling, and until then you should limit the scope of variables as much as possible. Thus, the second example is preferred.

Narue 5,707 Bad Cop Team Colleague

There are two possible interpretations here:

1) Any discussion of P2P software is prohibited because the software may be used to obtain pirated software or other illegal materials.

2) The clause refers to the specific act of obtaining illegal materials using a P2P program, so discussion of legal use is not prohibited.

The former is easier to follow and easier to enforce, but probably a bit too strict. The latter makes more sense but is easier to accidentally violate, and this is a problem because Keep It Legal doesn't allow for warnings. The first offense results in a five point infraction.

For the sake of simplicity, I'd recommend the first interpretation until Dani (she wrote it) replies with the intention of that clause.

Narue 5,707 Bad Cop Team Colleague

Moved to the correct forum.

Narue 5,707 Bad Cop Team Colleague

Use a loop to read more than one line:

ifstream in ( "myfile" );

if ( in ) {
  string line;

  while ( getline ( in, line ) )
    cout<< line <<'\n';
}
Narue 5,707 Bad Cop Team Colleague

>But my point is , i am not doing anything wrong by putting void main (void)
Do you honestly believe that you're not doing anything wrong by breaking an explicit rule?

>i admitted that you are right
No, you agreed with me superficially and then went right back to saying that your way isn't wrong. :icon_rolleyes:

I'm sorry Software guy, but you're a bad programmer and you shouldn't be writing code until you understand the problem with "it works for me" arguments.

Narue 5,707 Bad Cop Team Colleague

Erm, hexadecimal objective programs?

Narue 5,707 Bad Cop Team Colleague

The error gives you a line number, tell us which line it's referring to in the code you posted.

Narue 5,707 Bad Cop Team Colleague

Right...would you be kind enough to point out which line throws the error?

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

>I'm just wondering how to start doing this problem?
Start by understanding the process of converting infix to postfix. Once you have that, it's not much of a stretch to see how a stack could be used to do it. Or you could do a google search and get one of the many existing implementations to use as a template.

Narue 5,707 Bad Cop Team Colleague

>return 0;/*** was avoiding this line ****/
Lazy? Seriously, do 8 characters of boilerplate really make enough of a difference to totally destroy the portability and correctness of your code?

Narue 5,707 Bad Cop Team Colleague

>word occurences on c/c++ language database
Can you be more specific about what this "database" is? Is it just a text file, a relational database, or something else?

Narue 5,707 Bad Cop Team Colleague

>Fuck you all!!!
Right back at ya. Next time don't be a leech and you'll get a better response.

Narue 5,707 Bad Cop Team Colleague

>void main (void)
This is not (and never has been) correct C. The main function returns int.

>a variable of type char is just an 8-bit int.
Just to be thorough, even though your reply is over a week old, char is only guaranteed to be at least eight bits.

Narue 5,707 Bad Cop Team Colleague

>If the person did not have the qualifications for the position based on their resume
>then one would be logical to assume that you would not be interviewing them.
One would be wrong in that case. It's easy to get through the preliminary culling processes to the interview and be completely clueless. I cut about half of my interviews short because it's obvious the candidate is woefully unqualified for the job even though their resume is technically accurate.

Narue 5,707 Bad Cop Team Colleague

>but you actually named your post "Do my homework for me."?
I named the thread when I split the post from an existing thread.

>Also, doubly linked lists are NOT reffered to as DLLs.
Actually, they are. Especially in books you'll see mention of DLL and SLL to refer to double and single linked lists.

Narue 5,707 Bad Cop Team Colleague

>It may not work properly on all the compilers.
Please quote chapter and verse from the standard that proves this.