Narue 5,707 Bad Cop Team Colleague

>Okay, while continuing to search, I came up with this:
>http://msdn.microsoft.com/en-us/libr...=VS.80%29.aspx

_Smanip is a Microsoft-ism. Don't expect code using it to compile anywhere except Visual C++. The concept behind _Smanip is trivial anyway:

#include <iostream>
#include <iomanip>

struct fillblank {
  int _l;

  fillblank ( int l ): _l ( l ) {}

  friend std::ostream& operator<< ( std::ostream& os, fillblank fb )
  {
    for ( int i = 0; i < fb._l; i++ )
      os << ' ';

    return os;
  }
};

int main()
{
  std::cout << "10 blanks follow" << fillblank ( 10 ) << ".\n";
}

The arguments are actually constructor arguments, which are then stored as data members in a temporary object and an overloaded << operator is called on the stream using that temporary object. It's elegant and works very well.

Narue 5,707 Bad Cop Team Colleague

>i searched how to use three conditions in conditional operator but didn't find any where
Then I guess you didn't look in this thread. My first reply gives you this:

int d = a < b ? a < c ? a : c : b < c ? b : c;

My previous reply showed you a conversion to if statements from which you can derive the equivalent code:

int d;

/* d = a < b ? a < c ? a : c : b < c ? b : c */
if ( a < b ) {
  if ( a < c )
    d = a;
  else
    d = c;
}
else {
  if ( b < c )
    d = b;
  else
    d = c;
}
Narue 5,707 Bad Cop Team Colleague

>why it is printing the Maximum value among those three input values ?
It isn't. If b is greater than or equal to a, but c is less than b, your code will erroneously print c rather than b. It helps if you write the equivalent if statement to see the logic flow:

/* d=a>b? b>c? a:b:c */
if ( a > b ) {
  if ( b > c )
    d = a;
  else
    d = b;
}
else {
  d = c;
}
Xufyan commented: Ty.:)..Xufyan +0
Narue 5,707 Bad Cop Team Colleague

>how can i write a code for three conditions ?
I assume you're looking for the ugly nesting solution:

int d = a < b ? a < c ? a : c : b < c ? b : c;

Which looks a lot like line noise and should be avoided in well written code. A feasible alternative is using a macro to hide the ugliness:

#define min(a, b) ((a) < (b) ? (a) : (b))

int d = min ( a, min ( b, c ) );
Narue 5,707 Bad Cop Team Colleague

Have you checked a C reference? We're generally miffed when people ask questions that are easy to look up.

Narue 5,707 Bad Cop Team Colleague

>we need to do our project using Turbo C only
Turbo C was/is reasonably conformant to C89. As long as you don't use silly TurboC-isms like conio.h or graphics.h and other non-standard features, code written on a modern compiler is highly likely to work on Turbo C.

>If he says otherwise, send him here.
That's an excellent idea, but I have yet to see it bear fruit. First and foremost, the instructor doesn't always have a say in the contents of the curriculum or the tools used. Second, what teacher is going to go to a forum to hear random people whine and flame? I wouldn't waste my time like that either if I were the OP's teacher. ;)

Narue 5,707 Bad Cop Team Colleague

>i was trying to find code or solution without using stdlib.h
Unless you need something stronger than rand, it's best to keep to the standard libraries. However, implementing your own random number generator is an entertaining exercise.

>May I ask if Is it safe to download Turbo C in brothersoft.com
If I say "NO! It's a virus!", will you forget about Turbo C and use a more up-to-date compiler? I'm not against lying if it benefits everyone. :D

Aia commented: Liar! It is a trojan! :D +8
jonsca commented: Can't say you didn't try... +3
Narue 5,707 Bad Cop Team Colleague

>Am I right in thinking there's a typo with this bit of code though:
Yes, the test should be against value rather than _field. Serves me right for writing untested code inline. ;)

Narue 5,707 Bad Cop Team Colleague

Your first example is a syntax error because it's neither a method nor a property. If you add a parameter list, it works and becomes a method:

public int ShiftsLeft() {
  return shiftsToWork - shiftsWorked;
}

>Can someone tell me the difference between the two
Methods are named executable blocks of code that take a predetermined number and type of parameters and return a single value (possibly of type void). Properties are a controlled interface around (typically) a single class field. Let's look at it from the perspective of a lack of properties:

class Test {
  private int _field;
}

Let's say you want to give public access to _field, but you still want _field itself to be private. Unrestricted access could break your class' assumptions about that field. For the sake of argument, say the value of _field should be in the range of [0,100).

In the absence of properties, one might use methods for the interface:

class Test {
  private int _field;

  public int GetField() { return _field; }
  public void SetField(int value)
  {
    if (0 <= _field && _field < 100) {
      _field = value;
    }
  }
}

Then callers can access _field through the restricted interface and all is well, yes?

Test foo = new Test();

foo.SetField(55);
Console.WriteLine(foo.GetField());
foo.SetField(10000);
Console.WriteLine(foo.GetField());

The syntax is kind of awkward, but it's not horrible. Properties are simply another way to do the same thing with a more intuitive syntax:

class Test {
  private …
apegram commented: Excellent lexplanation. +1
JohnnyT commented: A superb explaination and it really helped me out. Thanks +6
Narue 5,707 Bad Cop Team Colleague

>but why the variable number_value is 0.
>I expect the value of 7.

Deep under the hood (for g++), number_value is getting set to 0.0 because the "a" is read as a floating-point value and fails to be converted by strtod, which returns 0 if no conversion can be made. Essentially g++ uses a reference to number_value as the working result throughout the process.

On the other hand (to explain vmanes' results), Visual Studio uses a temporary local variable to perform the conversion and only sets the reference to number_value on a successful conversion.

In this case, Visual Studio is correct and g++ is not because these conversions are performed through the num_get facet, which is required to leave the value reference unchanged on failure. g++ doesn't meet that requirement.

yapkm01, it would help to know what compiler you're using. For that lack, my answers are based on the two compilers vmanes tested with.

vmanes commented: Nice explanation of the behind the scenes actions +5
Narue 5,707 Bad Cop Team Colleague

First set the data source for the combobox column as you would for just a regular combo box. Then set the DataPropertyName property for the combobox column to the name of the column you want to bind to in your data set.

Narue 5,707 Bad Cop Team Colleague

>the error might be here ...
It might.

>new_student->name = (char *)malloc(8 * sizeof(char));
You allocate memory to name, all is well so far (barring minor nits).

>new_student->name = "Michael\0";
Bzzt! You've now overwritten your only reference to the memory just allocated. Not only is this a memory leak, if you call free on a pointer that wasn't returned by malloc and friends, bad things happen. You probably want to use strcpy to copy the contents of that string literal into name.

It should go without saying that this bug is repeated several times and you should address each instance rather than just name. I used name as the example.

Narue 5,707 Bad Cop Team Colleague

Double the brace up:

Console.WriteLine("{0} ... {{", var1);

MSDN clearly states what happens in the format string:

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.

Salem commented: And the RTM award goes to..... :) +19
ddanbe commented: This is what discerns a pro from a learner like me :) +6
Narue 5,707 Bad Cop Team Colleague

>I want to order the ParentList so the Chromosome Class with the
>smallest value is at the top and the one with the highest is at the bottom.

Okay, that's completely different. Note that C# already has something called attributes that aren't the same thing as class fields or properties. And you have a list of objects, not a list of classes. Accurate terminology goes a long way toward not confusing people. :)

Anyway, you want something more like this:

using System;
using System.Collections.Generic;

namespace JSW
{
    static class Program
    {
        static void Main()
        {
            var chromosomes = new List<Chromosome>();
            Random rand = new Random();

            for (int i = 0; i < 10; i++)
            {
                chromosomes.Add(new Chromosome(rand.Next(100)));
            }

            chromosomes.ForEach(x => Console.WriteLine(x.Punishment));
            Console.WriteLine();

            // This call to sort is the part you're interested in
            chromosomes.Sort(
                delegate(Chromosome x, Chromosome y)
                {
                    return x.Punishment - y.Punishment;
                });

            chromosomes.ForEach(x => Console.WriteLine(x.Punishment));
        }
    }

    class Chromosome
    {
        public int Punishment { get; set; }

        public Chromosome(int punishment)
        {
            Punishment = punishment;
        }
    };
}

If you're a beginner then you probably want to read up on delegates and anonymous methods/lambdas to fully understand everything in the example.

apegram commented: Finally, someone showing LINQ, extension methods, and delegates. It's rare around here. +1
Narue 5,707 Bad Cop Team Colleague

Well, how you do it depends on a few things that you didn't specify, so I'll just throw out one possible solution to get your creative juices flowing:

using System;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;

namespace JSW
{
    static class Program
    {
        static void Main()
        {
            List<Type> classes = new List<Type>(
                new Type[] { typeof(Foo), typeof(Bar), typeof(Baz) });

            classes.ForEach(c => Console.WriteLine(c));
            Console.WriteLine();

            var sorted = classes.OrderBy(c => GetDescription(c)).ToList();

            sorted.ForEach(c => Console.WriteLine(c));
        }

        static string GetDescription(Type type)
        {
            Attribute[] attributes = Attribute.GetCustomAttributes(type);
            var descr = (DescriptionAttribute)attributes.SingleOrDefault(
                attr => attr is DescriptionAttribute);

            return descr != null ? descr.Description : "(no description)";
        }
    }

    [Description("B")]
    class Foo { }

    [Description("A")]
    class Bar { }

    [Description("D")]
    class Baz { }
}
Narue 5,707 Bad Cop Team Colleague

>Shouldnt it except any data type?
Templates aren't magic. When you call total with an int argument, type deduction turns T into int . Once you instantiate the template, you turn T into a single concrete type.

Narue 5,707 Bad Cop Team Colleague

I interpret it as the function is supposed to perform input as well as calculate the total. So your main would be something like so:

int main()
{
  int n = 10;

  std::cout<< total(n) <<'\n';
}
Narue 5,707 Bad Cop Team Colleague

>Like declare it with index of 1 and later on re-size it?
Not portably.

Narue 5,707 Bad Cop Team Colleague

You realize that the >> operator for input is is default delimited on whitespace, right?

Narue 5,707 Bad Cop Team Colleague

Array sizes must be constant in C++. If you want to get the size from input, you need to use a container class (such as std::vector), or simulate an array using pointers and dynamic memory.

Narue 5,707 Bad Cop Team Colleague

>score.thescore ->name = n;
Close. thescore is your dynamic array, not score :

score->thescore[i].name = n;

Apply that logic to your whole program.

Narue 5,707 Bad Cop Team Colleague

>let's call it Array
Let's not. How about you write a small program that fails, and one of us can tell you why.

>Can you show me the direction here?
No. Taken in isolation, your code is correct. Post something with more substance if you want help.

Narue 5,707 Bad Cop Team Colleague

>The first question to ask is where do function prototypes belong? Not in main().
Prototypes are not required to be at file scope. It's merely conventional because they usually reside in headers (which are usually placed at file scope) and used in multiple translation units. In the average case, prototypes at block scope would be duplicated in every block they're used, which would be tedious for all but the simplest of programs.

Narue 5,707 Bad Cop Team Colleague

>while (listPtr -> next != NULL) delete listPtr;
Unless listPtr->next is NULL on the first iteration, you're deleting the same pointer multiple times. Try something more like this for the whole destructor:

while (listPtr != NULL) {
  NodePtr save = listPtr->next;
  delete listPtr;
  listPtr = save;
}
Narue 5,707 Bad Cop Team Colleague

>So you mean it have nothing to do with human readable part.
Pretty much. We're talking about individual tokens such as operators, numbers, identifiers, etc... The parser should simply be able to take a token and work with it rather than try to recognize what it represents first.

Narue 5,707 Bad Cop Team Colleague

The lexer turns source code into something that's easier to parse. That's really all there is to it. ;)

Narue 5,707 Bad Cop Team Colleague

argc is there for a reason, use it to determine if argv[1] even exists.

Narue 5,707 Bad Cop Team Colleague

>i - 1/2
This raises some red flags. 1/2 is 0 because both operands are integers. i - 0 is probably not what you wanted. You probably wanted the whole expression to be evaluated as floating-point:

i - 1.0 / 2
Narue 5,707 Bad Cop Team Colleague

Just because it compiles without errors doesn't mean the code works. Your I_simpson function is hanging, which means it doesn't return, which means you don't get any output.

Narue 5,707 Bad Cop Team Colleague

It's not the namespace, it's the stuff in the namespace that gets redefined. Ideally you would put only declarations in a header and definitions in a separate implementation file. But you can help alleviate the problem with inclusion guards.

Narue 5,707 Bad Cop Team Colleague

>This is the first time I've ever seen this and I'm interested in any
>reasoning why we shouldn't just remove it to eliminate code bloat.

I can't claim to know what the original author was thinking, but I'm a fan of the double inversion for forcing an integer into a strict boolean 0 or 1.

Narue 5,707 Bad Cop Team Colleague

>So is this an invalid statement then:
>Remember, a shift is not a rotate.

The statement is valid. It refers to the value being shifted, not the shift amount.

>It sounds like you are telling me this post is a junk post then...
Absolutely. dusktreader was probably relying on how a single implementation interprets the undefined behavior rather than the standard language definition. Here's what the standard says (emphasis mine):

shift-expression:
additive-expression
shift-expression << additive-expression
shift-expression >> additive-expression

The operands shall be of integral or enumeration type and integral promotions are performed. The type of the result is
that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to
the length in bits of the promoted left operand.

The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are zero-filled. If E1
has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo
ULLONG_MAX+1 if E1 has type unsigned long long int, ULONG_MAX+1 if E1 has type unsigned long int, UINT_-
MAX+1 otherwise. [ Note: the constants ULLONG_MAX, ULONG_MAX, and UINT_MAX are defined in the header <climits>.
—end note ]

The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type …

Narue 5,707 Bad Cop Team Colleague

>If you shift more than 31-bits left
The behavior is undefined.

>The issue is the fact that 32-64=-32 which on a right shift operation is 32-bits left.
No, that's undefined too. If you shift in either direction by a negative value or by a value greater than or equal to the number of bits in the target, the behavior is undefined.

>Some of the results don't seem correct, but they're periodic none the less. How???
It's generally best not to try explaining undefined behavior. Your results could be wildly different on another compiler, so you don't gain as much as you would by learning that what you did is undefined. :)

Narue 5,707 Bad Cop Team Colleague

>cin >> length, width;
This doesn't do what you think. A comma is inapproriate, it should be another >> operator:

cin>> length >> width;

>cout << " The total cost will be " << areaR << endl;
>areaR= (length * width);
>cin >> areaR;
>cin >> areaR;

This is nonsensical. The ordering seems goofy. You print areaR before assigning it a suitable value, then fill it with user input twice in a row?

Narue 5,707 Bad Cop Team Colleague

>Would that solution still work?
Yes, and it would have saved us both some time if you had simply tested this for yourself, seeing as how I gave you a complete program. Do you not have a compiler installed?

Narue 5,707 Bad Cop Team Colleague

The only things int can hold are whole numbers. Any precision you assign to an integer will be truncated.

Narue 5,707 Bad Cop Team Colleague

Here's one way with sscanf:

#include <stdio.h>

int main(void)
{
  const char *src = "-6 1 2 3 6";
  int pos = 0;
  int n = 0;
  int x;

  while (sscanf(src + pos, "%d%n", &x, &n) == 1) {
    printf("%d\n", x);
    pos += n;
  }

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

The .* syntax only says what object you're applying the pointer to; you still need to do everything necessary to access the pointer itself:

(b.*b.fnptr)();

In your code, the compiler is looking for fnptr in the unadorned scopes, but fnptr is actually a member of Base, so you need to use the full name of b.fnptr .

Doing the double membership is awkward and can be confusing, so perhaps an intermediate local variable is a better solution:

void (Base::*p)() = b.fnptr;
(b.*p)();
Narue 5,707 Bad Cop Team Colleague

>Is there any way to get around this?
Sure, don't use a pointer for the element type of the x array:

void test6 () {
  printf ("test6:\n");
  char x[2][STACK_NAME_SIZE];
  push ("Zero");
  push ("One");
  pop (x[0], STACK_NAME_SIZE);
  pop (x[1], STACK_NAME_SIZE);
  push("Two");
  push("Three");
  printf ("%s\n", x[0]);
  printf ("%s\n", x[1]);
}
Narue 5,707 Bad Cop Team Colleague

>As it stands now, I am getting a segfault.
I'm not surprised. You have the right idea in making a copy of the name to return, but you're attempting to return a pointer to a local variable, which is a bad idea. When a function returns, the local variables are conceptually destroyed. Thus, you can't use a pointer to the destroyed data.

If you don't want to use malloc, you really only have the choice of using an externally defined array to hold the name. For example:

char *pop ( char name[], size_t size )
{
  struct StackElement *save = stackTop;

  if ( strlen ( save->name ) >= size )
    return NULL;

  strcpy ( name, save->name );
  stackTop = save->next;
  free ( save );

  return name; /* Note: no indirection here */
}
Narue 5,707 Bad Cop Team Colleague
if ((letter >= 'A' && letter <= 'Z' ) || (letter >='a' && letter <= 'z'))
{
  printf(" %c is a CONSONANT\n", letter);
}

If it's a letter at all, you always say it's a consonant. If you separate error checking from processing, you can eliminate that problem:

if ( isalpha ( letter ) )
{
  switch ( toupper ( letter ) )
  {
  case 'A': case 'E': case 'I': case 'O': case 'U':
    printf ( "%c is a vowel\n", letter );
    break;
  default:
    printf ( "%c is a consonant\n", letter );
    break;
  }
}
else
{
  printf ( "Not a letter\n" );
}
jonsca commented: You are a true poetess of the source code! +2
Narue 5,707 Bad Cop Team Colleague

>Recently I replaced the 6.0 with Visual C++ 2008 Express.
>Now, none of my older code will compile.

I'm not surprised. One of the biggest things Visual C++ 6 supports that newer versions do not is the prestandard headers:

// Compiles in VC++6, but not VC++2008
#include <iostream.h>

int main()
{
  cout<<"Hello, world!\n";
  return 0;
}

There are many other things like that in Visual C++ 6, but I suspect that's your biggest problem. The easiest way to get around it is using the standard header names and a using directive:

// Compiles in VC++2008 (also VC++ 6)
#include <iostream>

using namespace std;

int main()
{
  cout<<"Hello, world!\n";
  return 0;
}

Another huge failure point of Visual C++ 6 is the STL. However, it's hard to tell you what other changes to make without seeing your code or the errors you're getting.

Narue 5,707 Bad Cop Team Colleague

>If so, how do I write this constant address?
Cast it to the appropriate pointer type:

int *p = (int*)1;

However, it's strongly recommended that you don't do this unless you really know what you're doing.

Narue 5,707 Bad Cop Team Colleague

>This library is powerful, helpful, and relatively easy
>to learn, and it works in all c++ compilers.

Visual C++ 6 has a notoriously broken standard library (especially the STL). But with a few caveats, you're right:

  1. Compilers that were released before or around 1998 may not conform well at all.
  2. The standard library is updated with every revision of the C++ standard, so be aware what revision your compiler conforms to and what revision the features you want were introduced in.
Narue 5,707 Bad Cop Team Colleague

>try using
Oh, this should be good.

>scanf( "%s\n", &input );
No, sir. There are four distinct problems with this line:

  1. &input is incorrect because it's a type mismatch. scanf expects a pointer to char, not a pointer to an array of char. Just because it happens to work for you doesn't mean it isn't undefined behavior.
  2. Any whitespace in the format string will cause scanf to expect, well, any whitespace. That is, any type and any number of whitespace, and it reads whitespace until there's no more. End result, scanf will wait until you type a non-whitespace character.
  3. Never use the unadorned %s specifier. In fact, forget it exists, because it's gets in disguise. Instead, make sure to specify the number of characters you want to read (minus the terminating null character) as a field width.
  4. It's especially important that you check for errors when gathering data from an unsafe source.

Here's the correct call:

if ( scanf ( "%80s", input ) != 1 ) {
  /* Handle an input error */
}
Narue 5,707 Bad Cop Team Colleague

>fnptr =this->myvurtualfn1(); //error C2440: '=' : cannot convert from 'void' to 'void (__cdecl *)(void)'

  1. You're not taking the address of the member function, you're calling it.
  2. Pointers to member functions are not compatible with pointers to functions.

This might help with the syntax issues.

Narue 5,707 Bad Cop Team Colleague

You can supply a predicate to the sort template from <algorithm> that does the comparison:

#include <algorithm>
#include <vector>

void sort_object_list ( std::vector<sometype>& object_list )
{
  struct compare {
    bool operator() ( const sometype& a, const sometype& b )
    {
      return a.z < b.z;
    }
  };

  std::sort ( object_list.begin(), object_list.end(), compare() );
}
Narue 5,707 Bad Cop Team Colleague

>Should I be using fget instead of scanf?
Yes:

if ( fgets ( input, sizeof input, stdin ) == NULL ) {
  /* Handle input error */
}

>scanf( "%c\n", &input[81] );
For the record, input[81] is an invalid index because the size of your array is 81. Valid indices range from 0 to n-1. Thus, 80 is the last valid index for your array.

Narue 5,707 Bad Cop Team Colleague

>So what do you love to use when it come to C/C++?
I think love is a strong word for a tool. I like various features of the different IDEs I use, and choose among them based on my needs (if I choose to use an IDE at all). Visual Studio, Code::Blocks, and Borland Builder are the most commonly selected in my arsenal.

I have a tendency not to use an IDE on Unix/Linux, but programming without an IDE on Windows is irritating.

Narue 5,707 Bad Cop Team Colleague

>while(i < N - k) PartSum +=DataArray; i is never updated in this loop.