vijayan121 1,152 Posting Virtuoso

the pointer returned by string::c_str() is
a. a const char*. if you need a LPSTR (char*), you need to copy (strcpy) it to an array of chars
b. usable as a LPCSTR (const char*) only as long as you have not modified the string. you need to make your own copy if you want to use it for ever.

also, in your code TCHAR can be either a char or a wchar_t. if it is a char, a TCHAR* is already an LPSTR. if it is a wchar_t, a TCHAR* would be an LPWSTR. you need to convert from wide to narrow characters to get an LPSTR

vijayan121 1,152 Posting Virtuoso
// istream file, string str1, str2, str3
// read to the first colon
assert( geline( file, str1, ':' ) ) ;

// get first letter after the first colon
assert( geline( file, str2, ':' ) && !str2.empty() ) ;
char c = str2[0] ;

// read all the letters after the second colon
assert( geline( file, str3 ) ) ;
vijayan121 1,152 Posting Virtuoso
for (k = 0; k < MAXNUMS; k++) // calculate and display the voltage
{
volts[k] = current[[B]k[/B]] * resistance[[B]k[/B]];
cout << "The voltage is " << volts[k] << endl;
}
vijayan121 1,152 Posting Virtuoso
for (k = 0; k < MAXNUMS; k++) // Display and calculate the voltage
{
  cout << "The voltage is " << volts[k] << endl;
  volts[k] = current[i] * resistance[j];
}

not 'Display and calculate the voltage'
but 'calculate first and then display the voltage'
swap the two lines in the for loop.

vijayan121 1,152 Posting Virtuoso

a #import directive like
#import "<name of the ocx file or typelibrary>" no_namespace, raw_interfaces_only \
named_guids raw_native_types <any other #import attributes>

will generate a header file with the name <base name of tlb/ocx>.tlh. and this header is impliciltly #included.
the #import attributes specify options for generating the header file. this header contains C++ definitions of COM interfaces, types etc and can be directly used in your code.
instantiate the object using a CoCreateInstance. COM methods are seen by C++ as virtual functions. open the .tlh file to see the declarations and use the methods like normal virtual functions. once you are done, call Release instead of using delete.

vijayan121 1,152 Posting Virtuoso

> but how would u carry out this operation???
a= 10 + b; // it's not (b+10)

>> the problem you are facing can be eliminated by using friend functions.

friend functions are functions which are not members of the class, but are granted the same access rights as members of the class. they may be either free functions or member functions of another class.
operators (not all) can be overloaded using free functions.
the ideas are orthogonal; a free functions which oveloads an operator need not be a friend function.

#include <iostream>

struct modulo7
{
  explicit modulo7( int i ) : number(i%7) {}
  inline int value() const { return number ; }
  private: int number ;
};

inline modulo7 operator+( modulo7 first, modulo7 second )
{ return modulo7( (first.value()+second.value()) % 7 ) ; }

inline modulo7 operator+( modulo7 first, int second )
{ return modulo7( (first.value()+second) % 7 ) ; }

inline modulo7 operator+( int first, modulo7 second )
{ return second + first ; }

template< typename stream_type > inline
stream_type& operator<< ( stream_type& stm, modulo7 m )
{ return stm << m.value() ; }

int main()
{
  modulo7 a(6), b(4) ;
  std::cout << a+4 << ' ' << 4+a << ' ' << a+b << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

if you do not mind the viral license, you could use this. http://www.matteolucarelli.net/libreria/GetPrivateProfile/GetPrivateProfile.c.htm after sanitizing it by removing things like calls to atoi.

vijayan121 1,152 Posting Virtuoso

> Could you refer me to a site that explains exactly why it can't be initialized inside the class definition? I'd like to read up on the working behind why this is.

class Test
{
public:
    static const string MYARRAY[] ; // only a declaration
};
class Test
{
public:
    static const string MYARRAY[] = {"hello", "world"}; // also a definition
};

A class definition is one of the things that is not within the ambit of ODR; these may be present in more than one transltion unit provided the definitions are 'identical'. 'Non-extern objects and functions in different translation units are different entities, even if their names and types are the same.' but there should be only one instance of a static member of a class. Test::MYARRAY therefore has external linkage, class Test can appear in more than one translation unit. allowing the definition of Test::MYARRAY within the class definition would violate ODR.
http://en.wikipedia.org/wiki/One_Definition_Rule

vijayan121 1,152 Posting Virtuoso

you could write a custom allocator that tracks calls to allocate and deallocate.

#include <map>

template< typename T > struct myallocator : public std::allocator<T>
{
  typedef std::allocator<T> base ;
  typedef typename base::size_type size_type;
  typedef typename base::difference_type  difference_type;
  typedef typename base::pointer pointer;
  typedef typename base::const_pointer const_pointer;
  typedef typename base::reference reference;
  typedef typename base::const_reference const_reference;
  typedef typename base::value_type value_type;
  myallocator() throw() {}
  myallocator( const myallocator& a ) throw() : base(a) {}
  template <typename X> myallocator(
             const myallocator<X>& ) throw() {}
  ~myallocator() throw() {}

  template <typename X> struct rebind
  { typedef myallocator<X> other; };

  pointer allocate( size_type sz, const void* hint = 0 )
  {
    // record alloc request eg. ++num_allocs ;
    return base::allocate(sz,hint) ;
  }
  void deallocate( pointer p, size_type n )
  {
    // record dealloc request eg. --num_allocs ;
    return base::deallocate(p,n) ;
  }
};

template<typename T> inline bool operator==(
               const myallocator<T>&, const myallocator<T>& )
{ return true; }

template<typename T> inline bool operator!=(
               const myallocator<T>&, const myallocator<T>& )
{ return false; }

int main()
{
  std::map< int, float, std::less<int>, 
                myallocator<int> > testmap;
  for ( int i = 0; i < 1000000; i++ )
  {
    testmap[i] = (float)i;
  }
  testmap.clear();
}
Rashakil Fol commented: n/a +6
vijayan121 1,152 Posting Virtuoso

there are many simple tutorials available on the net. like this one http://www.huihoo.org/ace_tao/ACE-5.2+TAO-1.2/ACE_wrappers/docs/tutorials/online-tutorials.html

vijayan121 1,152 Posting Virtuoso

i'm sorry; it was a mistake made by me. to use the [] operator on a map, a default constructor is needed for the data.

struct Properties
{
    int Min;
    int Max;
    Properties( int a = 0, int b = 0 ): Min(a),Max(b){}
};

another way is to use the insert method of the map (instead of the operator[]).

vijayan121 1,152 Posting Virtuoso

one of the great classics of c++ deals with this topic in depth; 'Large-Scale C++ Software Design' by John Lakos. http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620

'More C++ Gems' by Stanley Lippman (F), Robert C. Martin (E) http://www.amazon.com/More-Gems-SIGS-Reference-Library/dp/0521786185/ref=sid_dp_dp/002-1745891-8300801 has three articles by John Lakos. these are a compact version of his seminal work.

note: the book is dated as far as c++ standards go; the issues it deals with are timeless.

vijayan121 1,152 Posting Virtuoso
struct Properties
{
  int mint;
  int maxt;
  int medt;
  Properties( int a, b, c ) : mint(a), maxt(b), medt(c) {}
};
typedef std::map < std::string, Properties > ProcessMap;

bool is_there( const ProcessMap& pmap, const std::string& pname )
{ return pmap.find(pname) != pmap.end() ; }

void insert( ProcessMap& pmap, const std::string& pname,
             int mint, int maxt, int medt )
{ pmap[pname] = Properties(mint,maxt,medt) ; }

void incr_times( ProcessMap& pmap, const std::string& pname )
{
   Properties& p = pmap[pname] ;
   ++p.mint ;
   // etc
}
vijayan121 1,152 Posting Virtuoso

mostUsed is a const. use a const_iterator. also a prefix increment instead of a postfix (efficiency)

for ( map<string,int>::const_iterator word = mostUsed.begin() ;
		word != mostUsed.end() ; ++word ) { /*...*/
FireSBurnsmuP commented: Impressive advise, Glad I got your help. +2
vijayan121 1,152 Posting Virtuoso

> it would include input via menu, mouse, focus etc.
>> please see the curses library to do those things.

ncurses has minimal support for mouse, none at all for focus/console window menu.

The ncurses library also provides a mouse interface. Note: his facility is original to ncurses, it is not part of either the XSI Curses standard, nor of System V Release 4, nor BSD curses. Thus, we recommend that you wrap mouse-related code in an #ifdef using the feature macro NCURSES_MOUSE_VERSION

from 'Writing Programs with ncurses' by Eric S. Raymond and Zeyd M. Ben-Halim

Portability
These calls were designed for ncurses(3X), and are not found in SVr4 curses, 4.4BSD curses, or any other previous version of curses.
The feature macro NCURSES_MOUSE_VERSION is provided so the preprocessor can be used to test whether these features are present .... Under ncurses(3X), these calls are implemented using either xterm's built-in mouse-tracking API or platform-specific drivers including Alessandro Rubini's gpm server, FreeBSD ysmouse, OS/2 EMX
If you are using an unsupported configuration, mouse events will not be visible to ncurses(3X) (and the wmousemask function will always return 0).

linux man page for ncurses

if you have a snippet where just mouse handling (forget console menu and focus) can be done using curses (portably), please post it; i would have learned something new.

vijayan121 1,152 Posting Virtuoso

> If you wish this to be "portable" across at least Windows and Unix, you should make use of the curses library.
if the definition of 'user input' is limited to characters typed in on the keyboard (except things like ALT+TAB) while the console/terminal has input focus, curses is a portable option. if 'user input' has a more general meaning, it would include input via menu, mouse, focus etc. i think it would be possible to write a library that would work in both windows and unix for these, but i do not know if such a library has been written.

vijayan121 1,152 Posting Virtuoso

> I think multiple threads is a bit beyond my experience...
it would be easier to use a console input buffer and wait for it to be signalled.

#include <iostream>
#include <iomanip>
#include <windows.h>
using namespace std ;

int main()
{
    HANDLE input = CreateFileA( "CONIN$", 
                    GENERIC_READ|GENERIC_WRITE, 0, 0, 
                    OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0 ) ;
    FlushConsoleInputBuffer(input) ;

    for ( int hour = 0; hour < 2 ; ++hour )
         for (int min = 0; min < 60 ; ++min )
             for ( int sec = 0; sec < 60 ; ++sec )
                 if( WaitForSingleObject( input, 1000 ) 
                        == WAIT_TIMEOUT )
                     cout << '\r' << hour << ':' << setw(2) 
                       << setfill('0') << min << ':' << setw(2) 
                       << setfill('0') << sec << flush ;
}
vijayan121 1,152 Posting Virtuoso

> I don't want any CRT in my application
do not use anything from the library that rquires CRT to be initialized. no malloc or new, no printf or streams, no statics requiring dynamic initialization or having non-trivial destructors, no atexit etc. and write your own entry-point function. here is a sample console based program:

#include <windows.h>
// link with switches /SUBSYSTEM:CONSOLE /ENTRY:"look_ma_no_main"
// to set these from within the ide
//    properties -> Linker -> System ->  SubSystem := Console
//    properties -> Linker -> Advanced ->  Entry Point :=  look_ma_no_main

extern "C" int look_ma_no_main()
{
  char hello[] = "hello world!\n\r" ; // assumes narrow character console
  DWORD ignore = 0 ;
  WriteFile( GetStdHandle(STD_OUTPUT_HANDLE), hello, 
                 sizeof(hello)-1, &ignore, 0 ) ;
  MessageBoxA( 0, "Hello World!", "No CRT", MB_ICONEXCLAMATION ) ;
  return 0 ;
}
vijayan121 1,152 Posting Virtuoso

The int returned by main() is a way for a program to return a value to "the system" that invokes it. On systems that doesn't provide such a facility the return value is ignored, but that doesn't make "void main()" legal C++ or legal C.

- stroustrup

on systems where it is supported, you could check the return value.
eg. return from a call to int system( const char* )
or in a shell eg. diff port-supfile standard-supfile > /dev/null || echo FILES ARE DIFFERENT

vijayan121 1,152 Posting Virtuoso
// ...
  for (i=0;i<3;i++)
  {
    
    cout<<"Name:";
    cin >> ws ; // eat up whitespaces that may be left in the buffer
    // or cin.ignore
    cin.getline(people[i].name, 20);//<--should be ok now
    
    cout<<"HC:";
    cin>>people[i].hc; // you will still have problems if the user
                   // enters non integer values here. or if the user 
                   // entered more than 19 characters for the name. to fix it
                   // see the first solution given in
                   // http://www.daniweb.com/forums/thread90228.html
  }
  // ...
vijayan121 1,152 Posting Virtuoso

"void main() -- main() has NEVER been a void, always an int, see this"

But I beg to differ a bit - once upon a time main( ) was a void function. Read K&R recently? The earliest C++ book I have, circa 1993, uses the form

main ( )
{
   //code here
}

not really. in C, a missing type defaults to an 'int'. and control reaching the end of a non-void function is at most a warning, not an error. even in the oldest K&R, you would not see

void main ( )
{
   //code here
}

here is an example:

foo()
{ return 5 ; } /* warning: return type defaults to `int' */

void bar()
{ return 5 ; } /* warning: `return' with a value, in function returning void */

int foobar() {}

main() /* warning: return type defaults to `int' */
{
  int (*pfn1)() = &foo ;
  void (*pfn2)() = &foo ; /* warning: initialization from incompatible pointer type */
}

/**
*****************  gcc 4.2.3 20071024 *********************
>gcc -std=c89 -Wall -Wreturn-type -pedantic -Werror -c cmain.c
cc1: warnings being treated as errors
cmain.c:2: warning: return type defaults to 'int'
cmain.c: In function 'bar':
cmain.c:5: warning: 'return' with a value, in function returning void
cmain.c: In function 'foobar':
cmain.c:7: warning: control reaches end of non-void function
cmain.c: At top level:
cmain.c:10: warning: return type defaults to 'int'
cmain.c: In function 'main':
cmain.c:12: warning: initialization from incompatible pointer type
cmain.c:12: warning: unused variable 'pfn2'
cmain.c:11: warning: …
vijayan121 1,152 Posting Virtuoso

no. i really meant even without gcc 4.3
i would use something like a std::vector< boost::any >
or a std::list< boost::variant<int,double,std::string> >
both of which are typesafe. and i would get the same functionality.
i also would not write functions that took several dozens of arguments; so even the overloaded template technique would be quite adequate for my limited needs.

Ancient Dragon commented: great solution +20
vijayan121 1,152 Posting Virtuoso

what you seem to be computing is the value of 22/7 to a number of decimal digits. it is an upper limit on the value of pi 3 + 10/71 < π < 3 + 1/7 (archemedis). for calculating the value of pi, see http://en.wikipedia.org/wiki/Pi#Calculating_.CF.80

vijayan121 1,152 Posting Virtuoso

> There are no compilers that support it
the output that i posted is with the code compiled by gcc 4.3 today; they are not my visualization of how it would look like in 2020.

> we still have to resort to stdarg.h to get variable argument functions
you may have to. i do not. even without gcc 4.3.

vijayan121 1,152 Posting Virtuoso

all my attempts at generating the functions using boost.preprocessor have resulted in code that was difficult to read and difficult to debug. (i really do not know how to debug preprocessor code other than by looking at the generated cpp output. and none of the versions i tried ended up being very readable).

but there is good news. c++ programmers will never have to use the unsafe and error-prone <cstdarg> ; c++0x has a solution. using variadic templates, we can write a typesafe function taking an arbitrary number of arguments of arbitrary types. http://en.wikipedia.org/wiki/C++0x#Variadic_templates

here is how you would write largest_of a variable number of values in c++0x.

#include <iostream>
#include <string>
// compile with gcc 4.3 with the -std=c++0x switch

template< typename T > inline 
const T& largest_of( const T& a, const T& b )
{ return a>b ? a : b ; }

template< typename T, typename ...REST > inline
const T& largest_of( const T& first, const REST&... rest... )
{ return largest_of( first, largest_of( rest... ) ) ; }

int main()
{
  std::cout << largest_of( 1, 9, 2, 8, 3, 7, 4, 6, 5 ) << '\n' ;
  std::cout << largest_of( 5.3, 8.9, -3.2, 17.8, 4.2, 7.0 ) 
          << '\n' ;
  const std::string s1("abc"), s2("2345"), 
                 s3("vufuk"), s4("ffyfyu") ;
  std::cout << largest_of( s1, s2, s3, s4 ) << '\n' ;
}
/**
>g++43 -Wall -std=c++0x -pedantic -Werror largest_of.cc && ./a.out
9
17.8
vufuk
*/
vijayan121 1,152 Posting Virtuoso

the easiest, least error-prone and the fastest way to copy an entire stream is this:
output_stream << input_stream.rdbuf() ;. if you are writing a utility like this, error messages are conventionally sent to cerr (not cout).

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

int main( int argc, char** argv )
{
  if( argc != 3 ) 
  {
    cout << "usage: " << argv[0]  << "<srce file>  <dest file>" ;
    return 1 ;
  }
  ifstream srce( argv[1], ios::binary ) ;
  if( !srce )
  {
    cerr << "could not open " << argv[1] << " for reading\n" ;
    return 2 ;
  }
  ofstream dest( argv[2], ios::binary ) ;
  if( !dest )
  {
    cerr << "could not open " << argv[2] << " for writing\n" ;
    return 3 ;
  }
  dest << srce.rdbuf() ;
  if( !dest )
  {
    cerr << "error while copying\n" ;
    return 4 ;
  }
}
vijayan121 1,152 Posting Virtuoso

> Why the following work:
bank . push_back ( data ); adds a new element to the sequence,

> and this doesn't:
bank [0] = data; tries to access and then assigns to a non-existing element.

> I've seen a lot of examples of STL vectors that was constructed inserting elements only with subscript operator.

vector<int> vec(10) ;
for ( int i=0;i<10;i++) vec [i]=i;

would work; there are 10 elements in the vector

vector<int> vec ;
for ( int i=0;i<10;i++) vec [i]=i;

would not; the vector is empty

vijayan121 1,152 Posting Virtuoso

> What if he wants 50 arguments, do you want to write 50 templates ?
no. i would strongly discourage him from trying to write functions which need more than seven or eight arguments.

> One function -- an infinite (almost) number of arguments
with the template: One function -- an infinite (almost) number of types.
and completely typesafe.

> and you don't have to screw around writing millions of templates or overloaded functions.
with the template: you don't have to screw around breaking your code each time (i suppose you would say millions of times) a new type needs to be supportd.

vijayan121 1,152 Posting Virtuoso
vector < map < int , char * > > bank;
      bank . reserve ( 10 );
      if ( bank [ 0 ] [ 0 ] == "a" ) //Memory access error

this code has *two* problems.
one: bank[0] is invalid; the vector is empty. there is no bank[0].
two: the code may not work even if bank[0] refers to a valid element of type
map < int , char * > map<>::operator[] would give a char*&.
operator == would give you a comparison between the two pointers. (what you need is strcmp).

it would be best to change the vector < map < int , char * > > to a
vector < map < int , string> > ; the == will then test equivalence. it could also avoid errors with the pointer being invalid or the c style string pointed to being overwritten.

> my exactly question is how can I use this type of association ( vector < map < type1 , type2 > > )
> without get into Mermory access violation errors? Is there a way to previously
> initialize that association in a manner that allow me to insert new element just doing
> bank [ i ] [ j ] = "some" ;

perhaps you could write a couple of functions

// bank[i][j] = str ;
void insert( map < int , char * >& bank, size_t i, 
                          int j, …
vijayan121 1,152 Posting Virtuoso

> You should be glad he didn't use the boost libraries. lolz
yes, you should be glad. i did considor using the boost preporocessor metaprogramming library http://www.boost.org/libs/preprocessor/doc/index.html to generate the overloaded max functions. but dropped the idea as i thought it may confuse many people.

vijayan121 1,152 Posting Virtuoso

> just how would that help the OP create a function that takes a variable number of arguments
you can call max with anything between 2 to 8 arguments; that is a variable number in my book. in any case, the C++ standard recommends some minimum values for such things as the maximum number of arguments for a function(256), the maximum nesting level of compound statements (256) etc. compilers can exceed these, but variable number of arguments does have an upper limit, no matter what technique you use. in my example, the upper limit is 8 (a reasonable value according to me. others may have different idea of what would be a reasonable value for an upper limit on number of arguments to be passed to a function. and they can create more overloads of max if they want).

> the arguments are all the same data type
yes, the OP wanted all arguments to be double values. and finding the largest implies that all arguments must support comparisons between them.

vijayan121 1,152 Posting Virtuoso

> I want to make a program with a max function taking any number of type double and returns the greatest of them

for a small number of arguments (upto about seven or so), you could use overloaded function names.

#include <iostream>
#include <algorithm>
template< typename T > inline
const T& max( const T& a, const T& b, const T& c )
{ return std::max( std::max(a,b), c ) ; }

template< typename T > inline
const T& max( const T& a, const T& b, const T& c, const T& d )
{ return std::max( std::max(a,b), std::max(c,d) ) ; }

template< typename T > inline
const T& max( const T& a, const T& b, const T& c, 
              const T& d, const T& e )
{ return std::max( std::max(a,b), max(c,d,e) ) ; }

template< typename T > inline
const T& max( const T& a, const T& b, const T& c, 
              const T& d, const T& e, const T& f )
{ return std::max( max(a,b,c), max(d,e,f) ) ; }

template< typename T > inline
const T& max( const T& a, const T& b, const T& c, const T& d, 
              const T& e, const T& f, const T& g )
{ return std::max( max(a,b,c,d), max(e,f,g) ) ; }

template< typename T > inline
const T& max( const T& a, const T& b, const T& c, const T& d, 
              const T& e, const T& f, const T& g, const T& h )
{ return std::max( max(a,b,c,d), max(e,f,g,h) ) ; }

int main()
{ …
vijayan121 1,152 Posting Virtuoso

> I would I put nodes into this list?
i did not realize on first reading that this might mean 'How would I put nodes into this list? '
standard library sequence containers provide the method push_back to add an element to the back of the sequence. there are also methods like insert, resize etc.

to add an element of type std::pair<CString,CString> to the back of a vector/deque/list

template< typename container > inline 
void foo( container& cntr, const CString& a, const CString& b )
{ cntr.push_back( std::make_pair(a,b) ) ; }
vijayan121 1,152 Posting Virtuoso

> OK, I am going to use the STL list.
unless insertion or removal of elements from the middle of the sequence are a requirement, or you need very strong guarantees in the presence of exceptions, a list is not the ideal data structure (efficiency, random access). if this is not the case, consider using a std::vector<> ( or if you need to insert or remove elements from either end of the sequence ) a std::deque<>

> I want to have each node have two strings
a. if you do not need to pass these strings to MFC functions, use std::string instread of CString
b. if you require just two member variables in a structure, you could use the ready made std::pair<>

std::vector< std::pair<CString,CString> > MyList ;
vijayan121 1,152 Posting Virtuoso

in functions InAscendingOrder and InDescendingOrder
a. use the size of the array passed to the function
b. make sure you do not make an 'off by one' error.
c. make them const-correct

//determine whether the array is in ascending order
bool  InAscendingOrder( const int array[], int number )
{
  for( int i=0 ; i<(number-1) ; ++i )
    if( array[i] > array[i+1] ) return false ;
  return true ;
}

int function InputArray
a. seed the random number generator in main, not in the function (or make sure that it is seeded only once)
b. the randomness of numbers generated by the c library rand() remains poor no matter what we do. if it is being used, this could generate somewhat better random sequences

//randomly generate array elements
void InputArray( int array[], int number)
{
  static int i = ( srand( time(0) ), 0 );
  for( i=0 ; i<number; ++i )
    array[i] = 1 + int( 100.0 * ( rand() / (RAND_MAX + 1.0) ) ) ;
}
vijayan121 1,152 Posting Virtuoso

> is there any way that i can add up all the values in a multiplication table?
you can do this in your mind

1*N + 2*N + 3*N + .... + (N-1)*N + N*N == 
          (1+2+3+...+(N-1)+N) * N == 
          ( ( N * (N+1) ) / 2 ) * N
vijayan121 1,152 Posting Virtuoso

> how can i make a new file and acces it from a class object?
to make a file and access it:

#include <iostream>
#include <fstream>
#include <string>
using namespace std ;

int main()
{
  const char* const file_name = "/tmp/my_newfile" ;
  // make a new file
  {
    ofstream file(file_name) ;
  }
  
  // access it (write)
  {
    ofstream file(file_name) ;
    file << "this is a test\nline 2\nlast line\n" ;
  }
  
  // access it (read)
  {
    ifstream file(file_name) ;
    string line ;
    while( getline(file,line) ) cout << line << '\n' ;
  }
}

the same code could also be in a member function of a class.

vijayan121 1,152 Posting Virtuoso

> to determine whether an array is sorted or not
go through the array element by element from the beginning.
if the element that you currently look at is smaller(as per the sort criterion) than the one you had just looked at before this, the array is not sorted. if there are no such elements, the array is sorted.

vijayan121 1,152 Posting Virtuoso

> What is best, linked lists or hash tables?
depends on what your requirement is. a list is a sequence container, used to keep a collection of elements. hash tables are associative containers, used for keeping a collection of key-value pairs with support for lookup on key.

> Is it ture that there is a ready-to-use linked list? Is there also a hash table?
there is a list implementation std::list<>
c++0x has a hash table, c++98 does not. but there is an implementation of an associative array std::map<> which would give you the same functionality.

> What advantages would there be to writing one from scratch?
you could learn quite a lot from the effort

> If I do go with MFC, what advantages are there?
support for ui programming in windows. everything else would be a disadvantage.
MFC and the standard c++ library are not mutually exclusive. look to MFC only if an equivalent facility is not available in the standard c++ library.

vijayan121 1,152 Posting Virtuoso

to get the command line elements, use the args passed to main:

int main( int argc, char** argv )
{
  copy( argv+1, argv+argc, 
        ostream_iterator<const char*>(cout,"\n") ) ;
}

to read a file line by line, use ::getline

int main( int argc, char** argv )
{
  ifstream file(__FILE__) ;
  string line ;
  int line_number = 0 ;
  while( getline(file,line) )
    cout << ++line_number << ": " << line << '\n' ;
}

to see if a string contains another string, use string::find

int main( int argc, char** argv )
{
  string line = "#include <algorithm>" ;
  string looking_for = "include" ;
  if( line.find(looking_for) != string::npos )
    cout << "found it\n" ;
}
vijayan121 1,152 Posting Virtuoso

it should. this is what i get.

#include <list>
#include <string>
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std ;

int main()
{
  string line = "abcd 2 4 6 8 10 1 3 5 7 9" ;
  list<int> myList ;

  if(line == "abcd 2 4 6 8 10 1 3 5 7 9")
  {
    istringstream stm(line) ;
    string eatit ;
    stm >> eatit ; 
    int number ;
    while( stm >> number ) myList.push_back(number);
  }
  copy( myList.begin(), myList.end(), 
        ostream_iterator<int>( cout, " " ) ) ;
  cout << '\n' ; 
}
/** 
>c++ list_int.cc && ./a.out
2 4 6 8 10 1 3 5 7 9
*/
vijayan121 1,152 Posting Virtuoso

here are a few utilities in bsd ports.
>cat /usr/ports/textproc/rtfreader/pkg-descr
RTF is the Microsoft Richtext Format, a more portable, mostly-ASCII
formatting language that is exported by word processors like MS Word.
These files generally have the extension .rtf, but occassionally have
.doc extensions as well. This parser is from the Microsoft spec,
"ported" to Unix systems.
WWW: http://www.fiction.net/blong/programs/#rtf

>cat /usr/ports/textproc/rtf2html/pkg-descr
A simple rtf2html converter. If no file is specified rtf2html reads from
standard input.
- ehaupt
ehaupt@critical.ch

>cat /usr/ports/textproc/rtfx/pkg-descr
rtfx converts RTF files into a generic XML format. It majors on keeping
meta data like style names, etc... rather than every bit of formatting.
This makes it handy for converting RTF documents into a custom XML
format (using XSL or an additional processing step).
RTF features supported: page breaks, section breaks, style names,
lists (various types), tables, footnotes, info block, bold, italic,
underline, super/sub script, hidden text, strike out, text color, fonts.
Author: Nielsen <nielsen at memberwebs.com>
WWW: http://memberwebs.com/nielsen/software/rtfx/

>cat /usr/ports/textproc/unrtf/pkg-descr
UnRTF is a command-line converter from RTF (Rich Text) to HTML, LaTeX,
PostScript, plain text, and text with VT100 codes. When converting to HTML, it
supports tables, fonts, embedded images, hyperlinks, paragraph alignment, and
more. All other conversions are "alpha" i.e. being newly developed.
WWW: http://www.gnu.org/software/unrtf/unrtf.html

>cat /usr/ports/print/rtf2latex/pkg-descr
rtf2LaTeX is a …

vijayan121 1,152 Posting Virtuoso

this would be less error-prone

if(line == "abcd 2 4 6 8 10 1 3 5 7 9")
  {
    istringstream stm(line) ;
    string eaten ;
    stm >> eaten ; 
    int number ;
    while( stm >> number ) myList.push_back(number);
  }
vijayan121 1,152 Posting Virtuoso

> The error seems to happen after the program is done with EVERYTHING.
for a general discussion of what this error means (buffer overrun), see
http://msdn2.microsoft.com/en-us/library/Aa289171(VS.71).aspx

vijayan121 1,152 Posting Virtuoso

ok, here is a (somewhat similiar) example.

#include <iostream>

class time_of_day // hh:mm:ss
{
  public :
    time_of_day( int hr, int min, int sec ) ;
    bool equals( time_of_day that ) const ;
    time_of_day advance_by_secs( int secs ) const ;
    int hour() const { return seconds_since_midnight / (60*60) ; }
    // etc
  private: int seconds_since_midnight ;
};

time_of_day::time_of_day( int hr, int min, int sec )
{
  // validate hr(0-23), min(0-59), sec(0-59)
  seconds_since_midnight = hr * 60 * 60 + min * 60 + sec ;
}

bool time_of_day::equals( time_of_day that ) const
{
  // called as: time_of_day_one.equals( time_of_day_two )
  // equals is a binary operation; compares two 
  // time_of_day variables for equivalence. 
  // one of them is the time_of_day on which the function
  // is called (time_of_day_one); identified by the this pointer
  // the other (time_of_day_two) is available as the arg 'that'
  return /* this-> */ seconds_since_midnight == 
              that.seconds_since_midnight ;
}

time_of_day time_of_day::advance_by_secs( int secs ) const
{
  enum { SECS_PER_DAY = 24*60*60 };
  time_of_day result = *this ; // make a copy
  result.seconds_since_midnight += secs ;

  // this is just to correct for overflow or underflow
  // could ignore this for now and focus on the rest.
  while( result.seconds_since_midnight < 0 ) 
     result.seconds_since_midnight += SECS_PER_DAY ;
  if( result.seconds_since_midnight >= SECS_PER_DAY ) 
     result.seconds_since_midnight %= SECS_PER_DAY ;
  return result ;
}



int main()
{
  int hr = 10, min=32, sec=45 ;
  time_of_day tod_one( hr, min, sec ) ;
  // now tod_one's member variable seconds_since_midnight 
  // has safely stored the value computed …
vijayan121 1,152 Posting Virtuoso

why don't you use this hint that your instructor has given you? it seems to be the simplest way to implement TMoney:
> Hint: we would suggest storing the whole amount as an amount of cents. In this case you will
> keep $1.20 as 120 and you will use division by 100 (amount/100) to get the number of dollars
> and modulo operator % (amount % 100) to retrieve amount of cents.
and avoid floating point altogether; for calculations, for input, for everything.

> It doesn't seem like I can just use t.add(), or t.times() just like that. How will the methods know what to work on?
the method TMoney::add should take an argument (amount to be added), multiply should also take an argument (the multiplier). so your code would look like t = t.add(t1), or t = t.times(3) etc. these are there in the code you posted originally. a const correct version of which would be

{
  // ...
  bool greater( TMoney b) const ;
  bool equals (TMoney b)  const ;
  TMoney add(TMoney b) const ; 
  TMoney times (int i) const ; 
  // etc.
};
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

try posing your query in a directx forum. eg.http://www.gamedev.net/community/forums/forum.asp?forum_id=10

vijayan121 1,152 Posting Virtuoso
ithelp commented: thanks. it help +2
vijayan121 1,152 Posting Virtuoso

> What was I doing wrong?

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

you only have a pointer to a VECTOR3, and it is uninitialized (contains some undefined value, not the address of a VECTOR3 object. the function oapiGetFocusShipAirspeedVector assumes that you have passed it the correct address of a VECTOR3 object and tries to fill up the VECTOR3 with values. the error is the same as in

double* ptr ; // uninitialized pointer, there is no double which it points to
*ptr = 8.9 ; // this is going to cause a lot of unpleasantness
char* pch ; // only a pointer, there is no array
strcpy( pch, "hello world" ) ; // this compiles, though you would wish later that it hadn't
// strcpy will try to fill up an array of chars starting at address pch