vijayan121 1,152 Posting Virtuoso
VECTOR3 speedvec; // first we define our vector which will recieve the data
oapiGetFocusShipAirspeedVector(&speedvec);//then we retrieve its x,y,z

if (GroundContact()==true && GetAirspeed() >13 && (speedvec[B].[/B]z>0))
{AddForce(_V(0,0,-5e3),_V(0,0,0));}

if (GroundContact()==true && GetAirspeed() >13 && (speedvec[B].[/B]z<0))
{AddForce(_V(0,0,5e3),_V(0,0,0));}

or

VECTOR3 _speedvec; // first we define our vector which will recieve the data
VECTOR3* speedvec = & _speedvec ;
oapiGetFocusShipAirspeedVector(speedvec);//then we retrieve its x,y,z

if (GroundContact()==true && GetAirspeed() >13 && (speedvec->z>0))
{AddForce(_V(0,0,-5e3),_V(0,0,0));}

if (GroundContact()==true && GetAirspeed() >13 && (speedvec->z<0))
{AddForce(_V(0,0,5e3),_V(0,0,0));}
vijayan121 1,152 Posting Virtuoso

> I'm never using that header file in my entire life again.
that is a wise decision.

> While we are at it, tell me since which year was it deprecated
it is not merely deprecated; it has been removed from the standard (c++98).
compilers still ship with the header though (to support legacy code).

since you are on a windows machine, you could download cygwin which has a more modern version of gcc. http://www.cygwin.com

vijayan121 1,152 Posting Virtuoso

> BTW the code you gave will generate errors.
yes, it would. modify as

cout   << "decimal: " << 30 << " hex: " << hex << 30 << " shifted left by 1 gives decimal: "
          << dec << (30 << 1) << " hex: "  << hex << (30 << 1) << endl << dec ;

> for using c++ with DJGPP
a. yes you have to use gcc on the command line (with a -X c++ switch in some cases).
b. for using c++ headers, see http://www.delorie.com/djgpp/v2faq/faq8_3.html
and you may have to use pre-standard headers <iostream.h> etc.

you really should not be using a pre-standard c++ compiler. anything released after about 2000 or so would be more or less ok.

vijayan121 1,152 Posting Virtuoso

> SinglyLinkedList<T> array;
it does not work if I add const int SIZE right before it
number of elements in c style arrays have the same restrictions as template parameters;
they must be constants known at compile time.

the best way is to use a std::vector instead of an array eg.

template < typename T > class Graph 
{
  public : 
    explicit Graph( size_t size ) : SIZE(size), array(size) {}
    bool AddVertex(T Data) ; 
    // ...
  private: 
     const size_t SIZE ;
     std::vector<T> array ;
};

i have by now become aware that a lot of people think that arrays are easier to use than vectors; if this is a homework and your teacher happens to be a member of this unfortunate group, allocate the array dynamically. eg.

template < typename T > class Graph 
{
  public : 
    explicit Graph( size_t size ) : SIZE(size), array( new T[size] ) {}
    ~Graph() { delete[] array ; }
    bool AddVertex(T Data) ; 
    // ...
  private: 
     const size_t SIZE ;
     T* array ;
     Graph( const Graph<T>& ) ;
     void operator= ( const Graph<T>& ) ;
};

the third option is make the number of elements a constant known at compile time (not very flexible) and revert to the first version. enum { numcourses = 9 };

vijayan121 1,152 Posting Virtuoso

> When you use typename, do you actually mean typename, or should I replace it with class?
in the context in which it is used, either typename or class will work. typename is preferred over class (class is there only to support legacy code).

> how do I define/instantiate an object of the type you listed?

int numcourses;
cin >> numcourses;
Graph<Course> graph(numcourses);
vijayan121 1,152 Posting Virtuoso

> I don't have a g++ compiler
if you have gcc (the gnu compiler collection), you also have g++ (it's c++ compiler)
use it from the same command line where you earlier used gcc.

> Do you all think if it's because I'm not passing any flags like in cl.exe /EHsc?
no.

> You just need to make situations to learn how to implement them, and enjoy the joys of programming.
do not look at language facilities like a mountaineer looks at mount everest. you will not enjoy the joys of programming very much. to learn how to implement them, you could use code like what you have written

cout   << "5 times 2 is " << (5 << 1) << endl
         << "20 divided by 4 is " << (20 >> 2) << endl;

or even better,

cout   << "decimal: " << 30 << " hex: " << hex << 30 << " shifted left by 1 gives decimal: "
          dec << (30 << 1) << " hex: "  << hex << (30 << 1) << endl << dec ;
vijayan121 1,152 Posting Virtuoso

> Any way to make it work with a variable?
no way (as a template parameter) if it is not a constant known at compile-time.

you could always do this:

template < typename T > class Graph 
{
  public : 
    explicit Graph( int size ) : SIZE(size) {}
    bool AddVertex(T Data) ; 
    // ...
  private: const int SIZE ;
};

template < typename T >
bool Graph<T>::AddVertex(T Data)
{
  // ...
}
vijayan121 1,152 Posting Virtuoso

to compile c++ code, use g++ (not gcc). eg.

>g++ -Wall -std=c++98 -pedantic -Werror expre_Shift_Operators.cpp -o expre_Shift_Operators.exe

> I'm still a bit confused as where to implement them
nowhere, unless you encounter a situation where you absolutely cannot do without them.

vijayan121 1,152 Posting Virtuoso

> speedvec pointer to variable receiving airspeed vector
you need to allocate memory to receive the result. use

VECTOR3 speedvec; // first we define our vector which will recieve the data
oapiGetFocusShipAirspeedVector(&speedvec);//then we retrieve its x,y,z
vijayan121 1,152 Posting Virtuoso
template <class T, int SIZE>
class Graph 
{
  bool AddVertex(T Data) ; 
  // ...
};

template <class T, int SIZE>
bool Graph<T, SIZE>::AddVertex(T Data)
{
  // ...
}
Ratte commented: Very helpful. +1
vijayan121 1,152 Posting Virtuoso

i don't know anything about oapiGetFocusShipAirspeedVector, but the code is incorrect unless the pointer is passed by reference and the library allocates memory for VECTOR3. (this is very unlikely).

// incorrect unless the function is declared as
// return_type oapiGetFocusShipAirspeedVector(VECTOR3*&) ;
VECTOR3 *speedvec; // first we declare our vector
oapiGetFocusShipAirspeedVector(speedvec);//then we retrieve its x,y,z

otherwise, it should be either (you allocate memory for VECTOR3)

VECTOR3 speedvec; // first we declare our vector
oapiGetFocusShipAirspeedVector(&speedvec);//then we retrieve its x,y,z

or (the library allocates memory)

VECTOR3 *speedvec; // first we declare our vector
oapiGetFocusShipAirspeedVector(&speedvec);//then we retrieve its x,y,z

check the documentation.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> In what instance specifically will this not work?
if your intent is only to discard whitespace characters from the stream, this will always work. that is the reason why the standard provides ws manipulator. and as it is difficult for a normal programmer to write this correctly, you should always prefer this over anything else.

however, if i want to read leading whitespace characters in the next line, this would not be suitable; it will skip over them. for this i would use the ignore member function of istream.

the problems i mentioned in the earlier post exist because the ws manipulator has to do a look ahead in the buffer, extract and remove characters till the next character that is left is a non-whitespace character. lookahead is notoriously difficult to implement correctly in a portable manner. the only lookahead that is guaranteed by the standard to succeed is the *one* character look ahead provided by streambuf::underflow. this is a protected virtual funcion of streambuf and you can not call it in a standard streambuf (you need to derive your own class). and all that extra leeway given to the ws maniplator is because of this.

vijayan121 1,152 Posting Virtuoso

> why is the compiler reading class declaration as struct declaration?
the compiler makes no distinction between a class or a struct in the declaration of the type. when the type is defined, the only difference between the two is the default access specifier.
so struct A { int i ; double d ; }; and class A { public: int i ; double d ; }; are identical definitions.
also, class C {/*....*/}; class D : public C {/*...*/}; is identical to struct C {private: /*...*/}; class D : C {/*...*/}; for example, the following code will compile without errors:

struct A ; class A ; struct A ;
int foobar( A arg1, A& arg2 ) ; // ok, use in name
//int foobar( A arg1, A& arg2 ) { return arg2.a = arg1.a ; };
// uncomment the above and you get the error '.... undefined type ....'
class A
{
  public : int a ;
};
struct A ; class A ; struct A ;
int foobar( A arg1, A& arg2 ) { return arg2.a = arg1.a ; }; // ok

class B ;

struct B : public A
{
  private : int b ;
  public : operator int() const { return a + b ; }
};

int main()
{
  struct A a1 ; 
  class A a2 ;
  class B b1 ;
  struct B b2 ;
  return a1.a + a2.a + b1.a + b2 ;
}

> power_i.h:21: error: invalid use of …

vijayan121 1,152 Posting Virtuoso

unfortunately, there is no portable way to discard unread characters from a stdio input stream. a language library technique would not necessarily be sufficient for this since unread characters can also accumulate in buffers other than the c++ streambuf (OS-level input buffers). to actively discard typed-ahead input (perhaps in anticipation of issuing a critical prompt), you'll have to use a system-specific technique; eg. for UNIX use tcflush.(You may also be able to use the curses flushinp function.)

you can consume the rest of a partially-read line with a simple code fragment like

while((c = getchar()) != '\n' && c != EOF)  /* discard */ ;

or you could use the ignore member function.

most often what you would want to do is consume whitespace characters remaining in the stream buffer *before* the next non-whitespace. for this, use the manipulator std::ws. for example, in your code, modifying the line getline(cin,sentance); to getline(cin>>ws,sentance); would be sufficient.

note: the problem of lookahead in a stream buffer is a difficult one, and ws is very different from other extractors. unlike other input mechanisms, the ws manipulator is not required to construct the sentry object prior to input. ws is also not a member function, so the exception policy for istream member functions does not apply to ws. this is different from the rest of extractors and all the other input functions (ws will not cause a tied stream to be flushed before extraction, it doesn't check the stream's exceptions or …

vijayan121 1,152 Posting Virtuoso

> intl were using floatl floatl members were using intl how to solve this !
to declare the floatl members using intl, a declaration of intl would suffice.
to define them, a definition of intl is required.

so do things in this order:
a. declare the classes first.
b. define the classes (which have declarations of their members)
c. define the members.
for example:

//********* header b.h ***************
#ifndef _B_H_INCLUDED_
#define _B_H_INCLUDED_
struct A ;
// A has been declared; we can now declare (not yet define) functions using A
struct B
{
  inline int b_fun( const A& a ) ;
  int bm ;
  A* a ;
  friend inline int b_friend( B& b, const A& a ) ;
};
#endif // _B_H_INCLUDED_
//////////////////////////////////////////////////////////////////

//********* header a.h ***************
#ifndef _A_H_INCLUDED_
#define _A_H_INCLUDED_
struct B ;

struct A
{
  inline int a_fun( const B& b ) ;
  int am ;
  friend inline int a_friend( A& a, const B& b ) ;
};
#endif // _A_H_INCLUDED_
/////////////////////////////////////////////////////////////////////

//********* header anything_else.h ***************
#ifndef _ANYTHING_ELSE_H_INCLUDED_
#define _ANYTHING_ELSE_H_INCLUDED_

#include "a.h"
#include "b.h"
// A and B have been defined; we can now define functions using A and B

int A::a_fun( const B& b ) { return am += b.bm ; }
int B::b_fun( const A& a ) { return bm += a.am ; }
int a_friend( A& a, const B& b ) { return a.am += b.bm ; }
int b_friend( B& b, const A& a ) { …
tnvkrishna commented: it's done with some kind of patience .i judge him based upon his previous replys.there was knowledge and patience in every one of them +1
vijayan121 1,152 Posting Virtuoso

if that still gives you problems, try this (old) link which does not require a language option (maybe, only english was available when this link was created)
http://go.microsoft.com/fwlink/?linkid=51410&clcid=0x409

vijayan121 1,152 Posting Virtuoso

> functions are defined in 5 different headers
what do these look like?

> a header allheaders.h which include all the header files
in what order?

vijayan121 1,152 Posting Virtuoso

converting ascii text files is trivial; you have a variety of tools. eg. tr, perl, awk, vi etc.in fact anything that can replace a cr-lf sequence with just a cr. eg. awk '{ sub("\r$", ""); print }' winfile.txt > unixfile.txt you could also use a utility called tofrodos which is available on a number of systems (under different names like "todos", "fromdos", "dos2unix", "unix2dos" etc.)
http://kb.iu.edu/data/acux.html
http://www.thefreecountry.com/tofrodos/

if the files are in unicode, these simple techniques will not work. unicode has a variety of newlines: CR (000D), LF (000A), CRLF (000D,000A), NEL (0085), FF (000C), LS (2028), and PS (2029). for a perl hack see http://www.onlamp.com/pub/a/onlamp/2006/08/17/understanding-newlines.html?page=3. it is easy in c++ to write a function that processes input character by character and does the necessary translations.

fread and fwrite are to i/o what memcpy is to memory. it reads or writes bytes into untyped memory (void*) without any formatting or interpretation. the stream should be opened in binary ("b") mode to prevent newline character translations by the underlying layers. for example,

int array[100] ;
// to write an array (binary) into afile 
fwrite( array, sizeof(int), 100, file ); 
// to read the array (binary) from a file 
fread( array, sizeof(int), 100, file );

struct some_struct mystruct  ;
// write
fwrite( &mystruct, sizeof(struct some_struct), 1, file ) ; 
// read
fread( &mystruct, sizeof(struct some_struct), 1, file ) ;

using these functions correctly is difficult; mainly because they do not distinguish …

vijayan121 1,152 Posting Virtuoso

this is the part that causes the problem:

do
     {
      x=line.find(oldstring); // *** what happens if you do not find it?
      line.replace(x,oldstring.length(),newstring);
      cout<<line<<endl;
     }
     while(x>=0);

also, for portability, make x a string::size_type and compare with string::npos eg.

string::size_type x = str.find(some_string) ;
if( x == string::npos ) { /* not found */ }
vijayan121 1,152 Posting Virtuoso

ater

cout<<"command?";
	  cin>>command;

you need to remove trainling whitespaces left in the buffer. modify the line to

getline( cin >> ws, datafind );//now this should be ok!

and you should be ok.

note: there are other logical errors in your code, locate them after you fix this one first.

vijayan121 1,152 Posting Virtuoso

on this page http://msdn2.microsoft.com/en-us/express/aa975050.aspx
go to the visual c++ 2005 express icon and choose the language from the 'select a language' control.
if the download does not start, put the entry in the 'select a language' control back to 'select your language' and then reselect 'english' once again. this worked for me when i tried it.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> as far as I know you don't declare a return type for constructors
explicit is a c++ keyword used to specify that a constructor cannot be used for implicit conversions. it is a declaration specifier (not a type). see http://cprogrammers.blogspot.com/2005/11/c-programming-explicit-constructors.html

> I thought it would be simple to determine wether a given float variable is a whole number or not.
it is (perhaps surprisingly) complicated. try out this program:

#include <iostream>

int main()
{
  std::cout << std::fixed << std::showpoint << std::boolalpha;
  float a = 1234567890.0 ; std::cout << a << '\n';
  float b = a+40 ; std::cout << b << '\n';
  float c = a-40 ; std::cout << c << '\n';
  std::cout << "a==b? " << (a==b) << '\n' ;
  std::cout << "(a+40)==a? " << ( (a+40)==a ) << '\n' ;
  std::cout << "a==c? " << (a==c) << '\n' ;
  std::cout << "b==c? " << (b==c) << '\n' ;
}

> i get an assertion error when I run the exe that says the vector subscript is out of range.
line 37: you are going out of range for small values of i. also, the number you are looking at may be a square of a prime number; so the < should be changed to a <=

for (prime_Iter=primes.begin(); 
          (prime_iter != primes.end() ) && (*prime_Iter * *prime_Iter <= i );
          prime_Iter++)
vijayan121 1,152 Posting Virtuoso

if MyControl is a polymorphic type:

// ....
try
{
  MyControl& control = dynamic_cast<(MyControl&>( mControl ) ;
  control.DoSomething();
}
catch( const std::bad_cast& )
{
  // TODO: cast failed; handle it
}
// ...

if not:

// ....
  MyControl& control = static_cast<(MyControl&>( mControl ) ;
  // it is the programmer's (this means your) responsibility to make sure
  // that this cast is correct.
  control.DoSomething();
// ...
vijayan121 1,152 Posting Virtuoso

> actually did my changes by adding line - 48 to it to make it back to '7'. line[i] - '0' would be much better; you program would then be not dependant on a particular character encoding.

vijayan121 1,152 Posting Virtuoso

>> can a friend method of a derived class use base class's protected members
friend functions have the same access rights as the members of the class. a derived class can access (only) inherited protected members of the base class. if a derived class can access the base class's protected members, friends of the derived class can access them too. and if a derived class cannot access the base class's protected members (because it has not inherited them), friends of the derived class also cannot access them. for example:

struct base_class
{
  protected: int protected_member ;
};

struct derived_class : base_class
{
  void member_function( derived_class& derived, base_class& base )
  {
     derived.protected_member = 9 ; // ok, inherited by derived_class
     derived.base_class::protected_member = 9 ; // also ok, inherited
     base.protected_member = 9 ; // error, not inherited by derived_class
  }
  friend inline void friend_function( derived_class& derived, 
                                     base_class& base )
  {
     derived.protected_member = 9 ; // ok, inherited by derived_class
     derived.base_class::protected_member = 9 ; // also ok, inherited
     base.protected_member = 9 ; // error, not inherited by derived_class
  }
};
vijayan121 1,152 Posting Virtuoso

you are making this way too complicated. to check if an integer is divisible by another, use the % operator instead of floating points.

> ..against the current vector of primes to see if any primes divide into the number evenly.
you need to check only up to the square root of the number. ie to check if 179 is a prime number, you only need to try dividing by 3, 5, 7, 11, 13

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cmath>
#include <cassert>
using namespace std;

struct prime_list
{
  explicit prime_list( int limit ) ;
  std::vector<int> primes ;
  private: bool is_prime( int number ) const ;
};

bool prime_list::is_prime( int number ) const
{
    int root = int( sqrt( double(number) ) ) + 1 ;
    assert( primes.back() >= root ) ;
    for( size_t i=1 ; i<primes.size() && primes[i]<=root ; ++i )
      if( number%primes[i] == 0 ) return false ;
    return true ;
}

prime_list::prime_list( int limit )
{
  if( limit > 2 ) primes.push_back(2) ;
  for( int number=3 ; number<limit ; number+=2 )
    if( is_prime(number) ) primes.push_back(number) ;
}

int main()
{
  prime_list list(500) ;
  copy( list.primes.begin(), list.primes.end(),
        ostream_iterator<int>(cout,"\n") ) ;
}
vijayan121 1,152 Posting Virtuoso

one way to implement dragon's algorithm:

#include <iostream>
#include <sstream>
using namespace std ;

enum { delimiter = '_' } ;

int digits_beyond_delimiter( const string& str )
{
  istringstream stm(str) ;
  if( stm.ignore( str.size(), '_' ) )
  {
    int number ;
    if( stm >> number ) return number ;
  }
  return -1 ; // error in string
}

string replace_number_after_delimiter( const string& str, int number )
{
  istringstream input( str ) ;
  ostringstream output ;
  char ch ;
  while( input.get(ch) )
  {
    output.put(ch) ;
    if( ch == delimiter ) break ;
  }
  output << number ;
  return output.str() ;
}


int main()
{
  const string str =  "06/11/07_13" ;
  int number = digits_beyond_delimiter( str )  ;
  cout << str << '\n' ;
  string result =  replace_number_after_delimiter( str, ++number ) ;
  cout << result << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> I was wondering why the windows compiler (specifically win32) tolerated such kind of error
past tense is correct; it does not any more.
microsoft c++ 6 was released prior to the the adoption of c++98; and behaved like c as far as for loops were concerned.
microsoft c++ 7 ( released 2003) provided c++98 conformance for this; but the default was backward compatibility with the earlier version. conformance had to be turned on explicitly ( /Zc compiler switch ).
microsoft c++ 8 ( released 2005) made c++98 conformance the default; but you can explicitly turn it off (again, with the /Zc compiler switch ).
typical microsoft; they haven't got to where they are without being pragmatic. microsoft's implementation of the c++ compiler is very good. stroustrup gave a talk on c++0x at the computer science club of waterloo university a couple of months back. here is an interesting extract from the question and answer session which followed:

Q: What’s your opinion about the Microsoft implementation of C++?
A: Microsoft’s implementation is the the best out there, they conform to the standards pretty well and the code generated is also good. GNU gcc is also good. Though, they want you to use their “Managed C++” called C++/CLI which is totally unportable. Apple does the same with their version of C++ which is Objective C/C++ and and so does GNU. They all play this game of trying to get users just to use their product …

vijayan121 1,152 Posting Virtuoso

> I should define _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE to the .cpp files where I use fread and fwrite?
yes, if you want to use files of sizes beyond the usual limit of 2GB on 32 bit systems. see the documentation for these macros http://www.delorie.com/gnu/docs/glibc/libc_13.html
if you are on linux, you also need to have these and -D_FILE_OFFSET_BITS=64 when you compile the kernel. eg.

CFLAGS += -Wall -O2 -D"LINUX" -D"_THREAD_SAFE" -D"_GNU_SOURCE"-D"_LARGE_FILES" -D"_LARGEFILE64_SOURCE" -D"_FILE_OFFSET_BITS=64"
vijayan121 1,152 Posting Virtuoso
if(truck <= v) // begin if statement
        {
          ... (dynamic_cast<Truck*>(vptr[k])) -> DOTLicense() ...
        }
          else
        {
          ...
        } // end if statement

the dynamic_cast operator in c++ is a run-time cast operator; the corrctness of the result of the cast is guaranteed by the implementation if the cast succeeds. if it fails, the result of a dynamic cast on a pointer is a zero pointer. and if you try to use the result without checking for succeess, a failed cast will cause unpleasant things to happen; typically a core dump.
assuming that the variable v has the right value of the VehicleType enum, if( truck <= v ) would be true for things other than a truck. and if that happens, (dynamic_cast<Truck*>(vptr[k])) would result in a zero pointer which you are trying to dereference. that the failure occurs at precisely the second element of the array is probably because you are using the same inputs every time to test your code. to debug the current code, print out the following:

Truck* pointer = (dynamic_cast<Truck*>(vptr[k])) ;
std::cout << "pointer: " << pointer 
                 << "  type of object: " << typeid( *(vptr[k]) ).name() << '\n' ;

unless you are trying to learn about dynamic_casts, consider using virtual functions instead of the type variable and casts.

vijayan121 1,152 Posting Virtuoso

> a template that converts an array of type T to an array of type char, which can then be used as the operand to sizeof to get the number of elements:

template <typename T, size_t N>
char (&array(T(&)[N]))[N];

another way to use the same template idea (which i find slightly more readable) is:

#include <cstddef>
#include <iostream>

template< typename T, std::size_t N > inline
std::size_t size( T(&)[N] ) { return N ; }

int main()
{
   int a[] = { 0, 1, 2, 3, 4, 5, 6 };  
   const void* b[] = { a, a+1, a+2, a+3 };
   std::cout << size(a) << '\t' << size(b) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

http://msdn2.microsoft.com/en-us/library/dk77e5e7(VS.80).aspx
and you should be using a std::ifstream (instead of a CFile).

vijayan121 1,152 Posting Virtuoso

once you read a line from the file, do not copy it if it starts with "telemetre_". eg.

const char remove_this[] = "telemetre-" ;
string line ;
while( getline(infile,line) )
{
  if( line.compare( 0, sizeof(remove_this)-1, remove_this ) != 0 ) 
     outfile << line << '\n' ;
}

to compare the first 16 characters`of two strings

if( string_one.compare( 0, 16, string_two ) == 0 ) cout << "first 16 chars match\n" ;
vijayan121 1,152 Posting Virtuoso

> DLLs only export functions, not classes
dlls export addresses of symbols. the symbols may be of anything which has external linkage. eg.

int symbol_one(double) { /* ... */ }
int symbol_two = 67 ;
class X
{
  int symbol_three(double) ;
  static int symbol_four ;
}; 
int X::symbol_three(double) { /* ... */ }
int X::symbol_four = 67 ;

symbol_one, symbol_two, X::symbol_three, X::symbol_four would all be exported.
note: in windows, the export is selective; so you would also require a __declspec(dllexport)

> how can i use the dlsym() to open a class name and its functions?
the real issue is symbols in c++ are decorated (mangled) with embeded type and namespace information. for free functions/variables at global scope, we could simply use an extern "C" to get rid of the decoration. for symbols in namespaces/classes, one option would be to create a 'map' in the shared library that maps user-specified names to symbol addresses. another would be to use the name mangling/unmangling routines from libiberty.

a more flexible approach would be to use virtual functions along with an extern "C" factory method. for example

struct A // common to .so and user program
{
  virtual int symbol_one(double) = 0 ;
  virtual ~A() {}
  // etc
};

struct A_imp : A // to be exported
{
  virtual int symbol_one(double) ;
  // etc
};

extern "C" A* create_A() { return new A_imp ; }

this avoids the name problem for member functions altogether; they are bound …

vijayan121 1,152 Posting Virtuoso

let us get this straight. it is usually a technical error for a class/struct to contain members which represent unencapsulated resources (unless the class/struct itself is an encapsulating wrapper for a *single* raw resource). here is a simple example:

struct book
{
  book( const char* t, const char* a ) ;
  ~book() ; // required
  book( const book& that ) ; // required
  book& operator= ( const book& that ) ; // required
  char* title ;
  char* author ;
};

book::book( const char* t, const char* a )
{
  size_t title_len = strlen(t) ;
  title = new char[ title_len+1 ] ;
  strcpy( title, t ) ;

  size_t auth_len = strlen(a) ;
  author = new char[ auth_len+1 ] ; // this may fail (throw std::bad_alloc)
  // if it does, memory for title will leak. note: destructor of the book
  // being constructed will not (and should not) be called as the constructor
  // has not completed. so we have to scaffold this in a try/catch block.
  strcpy( author, a ) ;
}

the case with the copy constructor would be identical; the assignment operator is going to be even more messy. and as an exercise, try writing this code correctly:

struct foo { /* ... */ } ;
struct ebook : public book
{
  /*
  ...
  */
  foo* ptr ; // ebook 'owns' object pointed to by ptr
  ebook& operator= ( const ebook& that ) ; // implement this correctly
};

and once you have tried your hand at …

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> but if it is not year 2000, for example 2001. than this method wouldn't work?
a normal year has 365 days, a leap year has 366.
if in year n, jan 01 is a monday, jan 01 n+1 would be a tuesday if n is not a leap year ( 365%7 == 1 ) and a wednesday if n is a leap year.
jan 01 n-1 would be a sunday if n-1 is not a leap year and a saturday if n-1 is a leap year.
keep doing modulo 7 arithmetic all the way. you could even use modulo 7 values for days in a month; jan : 3, feb : 0/1, mar : 3, apr : 2 etc.

vijayan121 1,152 Posting Virtuoso

> when you say trampoline you mean this, right?
yes, except for the java and ojective-c usage of the term.

perhaps the use of trampolines that you would be most familiar with is that in a thread function. the compiler would compile the code for a thread function like any other function; you *can* safely call it like a normal function if you want. when a return is executed from a thread function (other than the one which executes main), an implicit call needs to be made to the system call (pthread_exit, ExitThread) which ends a thread with proper cleanup. this cleanup code would call cleanup/cancellation handlers, destroy any thread specific data, release the stack(s) etc. this is achieved by placing a trampoline on the thread stack (where the return address is expected).

another common example of trampoline use is in implementing tail recursion (eg. in languages of the lisp family). almost all the implementations of compilers/interpreters are in C. generating code for tail recursion in C (without growing the stack) is achieved by a number of trampoline bounces.

trampolines are also used to implement closures in C/C++. for example, in the (non-standard) implementation of nested functions in gcc. http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

posted by salem:

$ gcc -S -O2 foo.c && cat foo.s
_foo:
        pushl   %ebp
        movl    %esp, %ebp
        popl    %ebp
        ret
# The optimiser realises the results are never used, and the code is gone.

if we use the -fomit-frame-pointer switch, no frame …

vijayan121 1,152 Posting Virtuoso

is a java programmer trying to teach c++?
in c++, == always means logical equivalence.
as the language is not pointer-disadvantaged, you can compare addresses (again with an ==) to check for identity.
the case is different in java; you cannot comare strings for equivalence using an ==. see http://www.beginner-java-tutorial.com/java-string-comparison.html

void compare( const std::string& a, const std::string& b )
{
  bool equivalent = a == b ; // a and b are logically equivalent
  bool identity_equal = &a == &b ; // a and b are the same string object
}
vijayan121 1,152 Posting Virtuoso

> How can i see the assembly produced by the compiler{if it is possible}?
gcc: to generate assembly pseudo code, use the -S switch. eg. g++ -O2 -S -c whatever.cc to see the C code together with the assembly it was converted to: g++ -c -g -O2 -Wa,-a,-ad whatever.cc > whatever.asm microsoft: use one of /FA, /FAc, /FAs, /FAu compiler switches

> > From your experience where do you need to employ assembly while programming a real life project.
a. to implement something like the macros in <cstdarg> ( va_start, va_arg, va_end ) assembly may be required on some platforms.
b. defining things like sig_atomic_t, atomic_add etc. on some platforms.
c. to implement thunks and trampolines on some platforms.

n.aggel commented: helpful as always! +1
vijayan121 1,152 Posting Virtuoso

if they are const integral values known at compile time, and you define them as

enum { const_one = 567, const_two = -34, /* ... */ };

no storage would be allocated at all.

if the values are not known at compile time, and you declare them as

extern const int const_one ;
extern const int const_two ;
// etc

storage would be allocated once for each variable (there would be only one definition).

if they are const integral values known at compile time, and you define them as

const int const_one = 567 ;
const int const_two = -34 ;
// etc

these are constants known at compile time; the optimizer would optimize away allocation of any storage for these unless you take a pointer or reference to it eg.

const int* ptr = &const_one ;

one may be more concerned about the pollution of the global namespace by these 15 identifiers; in any case a good c++ program should have only main outside of any namespace.

vijayan121 1,152 Posting Virtuoso

your original code was fine *except* for that it did not take care of end of file correctly.

while(fin)
  {
    ch=fin.get(); // this may fail; if it does
    // ch will get the coerced value of char_traits<char>::eof()  
    while(ch==' ') 
    {
       if(count==0)
          fout.put(ch);
       ch=fin.get(); // this too may fail
       // ch will again get the coerced value of 
       // char_traits<char>::eof() which may or may not be == ' '
       count++;
     }
     fout.put(ch);
     count=0;
  }
vijayan121 1,152 Posting Virtuoso

> while(fin) is running endlessly ..
in general, when reading an entire file, it is a good idea to embed the input statement inside the while loop's condition. this would eliminate a lot of subtle errors. and the loop will exit once eof is reached. eg.

#include <fstream>
int main()
{
  std::ifstream in( "in.txt" ) ;
  std::ofstream out( "out.txt" ) ;
  char ch ; 
  bool last_was_space = false ;
  while( in.get(ch ) )
  {
    if( ch != ' ' )
    {
      out.put(ch) ;
      last_was_space = false ;
    }
    else if( !last_was_space )
    {
       last_was_space = true ;
       out.put(ch) ;
    }
  }
}

note: this will remove extra spaces; but will not take care of tab characters.

vijayan121 1,152 Posting Virtuoso

> How do you clear the console screen without any system-compatibility issues?
when the language (and the language libraries) do not provide a portable way of doing something, the usual approch is to look for a library with an api, allowing the programmer to write code in a portable way. ncurses is one that you could use. http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/intro.html
unix/linux : usually available as part of your base installation. if not, obtain from ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz
windows: download from http://gnuwin32.sourceforge.net/packages/pdcurses.htm

vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;

int main()
{
  const char SEPERATOR = '-' ;
  string date_string ;
  getline( cin, date_string ) ; // dd-mm-yyyy ;
  istringstream stm(date_string) ;
  int day=0, month=0, year=0 ;
  char seperator1 = 0, seperator2 = 0 ;
  stm >> day >> seperator1 >> month >> seperator2 >> year ;
  // validate that seperator1 and seperator2 are == SEPERATOR
  // validate day, month, year values
  // add up digits
  // etc.
}
vijayan121 1,152 Posting Virtuoso

this will not work at all (assuming you are using standard c++).

int row;
cin >> row;
int const ROWS = row;
int const SIZE = 30;
char word[ROWS][SIZE];

ROWS is not a constant known at compile time.

the right way to start learning c++ is by using std::vector and std::string instead of struggling with arrays and memory management. (these are much harder to handle correctly.) see http://www.research.att.com/~bs/bs_faq.html#how-to-start

to read a string from input, see http://www.research.att.com/~bs/bs_faq2.html#read-string
to read several values, see http://www.research.att.com/~bs/bs_faq2.html#simple-program
to understand why std::vector and std::string are much easier to use, see http://www.research.att.com/~bs/new_learning.pdf

to convert a char to upper case, this

if (word[count][0]) > 97 && (word[count][0] < 122)
      word[count][0] -= (word[count][0] - (word[count][0] -32))

is not needed; it also is not portable. instead use int std::toupper(int) (declared in header <ctype>). see http://www.cplusplus.com/reference/clibrary/cctype/toupper.html

if you are forced to use arrays as you start learning c++ (because of a teacher who should have known better),
a. define a sufficiently large array and keep track of how many elements are actually used
b. use a safer function like istream& get ( char* s, streamsize n, char delim ); eg.

#include <iostream>
#include <cctype> // for toupper
using namespace std;
int main()
{
  int const MAX_ROWS = 100 ;
  int const SIZE = 30;
  char words[MAX_ROWS][SIZE];
  cout << "Please enter a few words and i will change every letter into …
vijayan121 1,152 Posting Virtuoso

> ... It doesn't like my temporary array c and I can't get anything to sort ...
the compiler should not like it at all (it is not c++); and should give you an error.

int c[size]; //array c - the temporary array for sorting

size is not a constant known at compile time.

vijayan121 1,152 Posting Virtuoso

you could also
a. make the function const-correct
b. use a size_t instead of an int for the size

size_t smallestIndex( const int arr[], size_t size)
{
    size_t smallestIndex=0;
    int temp=arr[0];
    for(size_t i=1;i<size;i++)
    {
       if(arr[i]<temp)
       {
           smallestIndex = i;
           temp=arr[i];
        }
     }
   return smallestIndex;
}