vijayan121 1,152 Posting Virtuoso

> I think the original problem (causing the compiler error) is this:
> EventStream<complex<Lambda>> evstrTrain( ...
he is using Visual Studio C++ 2005. which accepts this (perhaps in anticipation of c++0x).

vijayan121 1,152 Posting Virtuoso

the code in the if-else is equivalent to

if(ARG::metrn==metrnSMD)
{ EventStream<complex<Lambda>> evstrTrain(fileTrain, evlsTrain); }
else
{ EventStream<Lambda> evstrTrain(fileTrain, evlsTrain); }

so the variable is not visible outside the scope of the if or else blocks.

one commonly used work around is to have a polymorphic base class. this works if the method signatures are identical for all the template specializations. eg.

#include <iostream>

struct event_stream_base
{
  virtual ~event_stream_base() {} // this is the destructor; 
   // there is a problem with the daniweb code formatter
  virtual void set_random_order(bool) = 0 ;
} ;

template< typename T > struct event_stream : event_stream_base
{
  explicit event_stream( const T& v ) : member(v) {}
  virtual void set_random_order(bool) 
  { std::cout << member << '\n' ; }
  T member ;
  // ...
};

int main()
{
  int a = 8 ;
  event_stream_base* pesb = 0 ;
  if( a > 5 ) pesb =  new event_stream<double>(2.34) ;
  else pesb =  new event_stream<int>(73) ;

  pesb->set_random_order(true) ;

  delete pesb ;
}

(another is to use a meta-function; but it may be prudent to ignore this option for now.)

vijayan121 1,152 Posting Virtuoso

The example that you are trying to use requires Visual Studio 2005.
from the error messages _Module undeclared identifier and CAtlExeModuleT undeclared identifier , it appears that you are
using an earlier version of visual studio (and ATL).

if you are using Visual Studio 2003, then the example code to use is in http://msdn2.microsoft.com/en-us/library/9d0714y1(VS.71).aspx

if you are using Visual Studio 2005, then the code you are currently using ( from http://msdn2.microsoft.com/en-us/library/9d0714y1(VS.80).aspx ) should compile without errors.

that the error you get refers to a global symbol _Module indicates that you are trying to use Visual C++ 6.0. this will not work at all. you need to move to Visual Studio 2003 or later.

note: if are still onVisual C++ 6.0, then it makes sense to go directly to Visual Studio 2008. in this case, use the example code from http://msdn2.microsoft.com/en-us/library/9d0714y1.aspx

vijayan121 1,152 Posting Virtuoso

> Error mentioned that my program requires a reinterpret_cast , a c_style cast or function_style cast.**
the code you posted does not give that particular error.
the two errors in your code are
a. #include <iostream.h> is not standard c++. replace this with #include <iostream> and using namespace std; b. main *must* return an int (not void).

when you run the code, there would also be a problem because of whitespaces left in the input buffer after cin>>choice ; . but you could deal with that after getting the program to compile without errors

vijayan121 1,152 Posting Virtuoso

ok. we need to revert to your post #31 and resume from there.
are you using visual VC++ 2005 (visual studio 2005)?
have you fixed the error '_Module is undefined' ?
and the error 'undefined base class' ?
and been able to compile your code?

vijayan121 1,152 Posting Virtuoso

> But it is returning some negative value. What is the problem in this code.
what is the value of HRESULT hr after this call? hr = mmap->get_MapID(&val); is it S_OK? if not what is it? in visual studio, you coul use the Error Lookup tool to get a human readable error description.

also, you would get better mileage from a forum if you do not direct questions to any specific member. even if that member is currently active, there may be others who are more knowlegeable about the problem and would be able to guide you in a better way.

vijayan121 1,152 Posting Virtuoso

change cout << os ; to cout << os.str() ;
os.str() gets the string from the stringstream.
cout << os ; is equivalent to cout << (const void*)os ; prints the pointer value.

vijayan121 1,152 Posting Virtuoso
Salem commented: good answer +15
vijayan121 1,152 Posting Virtuoso

see: More Effective C++: 35 More Ways to Improve Your Programs and Designs (Scott Meyers)
ITEM 27. Requiring or Prohibiting Heap-Based Objects.
and http://www.aristeia.com/BookErrata/M27Comments_frames.html

vijayan121 1,152 Posting Virtuoso

> I am using Microsoft visual C++ 6.0 compiler.Is it any problem with this compiler also? ... Is it possible to solve this one?

it would be a good idea to switch to a more modern compiler (eg. Visual Studio 2005 or Visual C++ Express 2005). but this particular problem is not because of the compiler. it seems that the activeX control that you want to use demands hosting. and if it is not hosted, fails requests to it. (you could verify this by trying to call the method in the activex control test container which ships with visual studio.) if that is the case, you need to write hosting code for the control. see post #24 for details.

vijayan121 1,152 Posting Virtuoso

read in as a char and check if it is 'H' or 'S'; set the enum accordingly.

PayType pt ;
  char c ;
  infile >> c ;
  if( c == 'H' ) pt = H ;
  else if( c == 'S' ) pt = S ;
  else infile.setstate( std::ios::failbit ) ;
vijayan121 1,152 Posting Virtuoso

> The links which u sent are referring to MFC code and not C++.
the links refer to ATL and not MFC. and with the change from WinMain to main, what you would have is a console application that uses the ATL library.

it is easy to access an activex control from C++ without using ATL or MFC (which are C++ libraries). you access it like any other com object. that is what you had been attempting to do. for example, this small piece of code http://msdn2.microsoft.com/en-us/library/bb249582.aspx will work. and it is quite easy to do away with the ATL wrapper for BSTR and the com smart pointer.

however, it is an entirely different matter to host a control in a control container. and that is what you need to do; the control that you are trying to use seems to require being hosted. this link http://msdn2.microsoft.com/en-us/library/aa768175.aspx#Container_Requirements gives the requirements for a control container. and without library support, implementing all this is going to be a huge and difficult task.

vijayan121 1,152 Posting Virtuoso

> Then that error I am getting like "CATASTROPHIC ERROR" :-(

this (along with the fact that CoCreateInstance and Release succeed)
usually means that the activex control is one that requires hosting.
for this you must provide an ActiveX control container.
You can use ATL for this purpose; this is a lot simpler
than implementing an ActiveX Control container from scratch.

see this msdn article on how to do this:
http://msdn2.microsoft.com/en-us/library/bb262335.aspx

as the control that you are trying to use not only requires
hosting, but also a license, you would need to use the CAxWindow2T
class instead of the CAxWindow used in the example. and use
CAxWindow2T::CreateControlLic
see http://msdn2.microsoft.com/en-us/library/328984a2(VS.80).aspx
and http://msdn2.microsoft.com/en-us/library/bycs8wcd(VS.80).aspx

with your current level of exposure to com, this is going to be a daunting task.
probably, the easiest way for you to right now would be to copy this
msdn sample Hosting ActiveX Controls Using ATL AXHost
http://msdn2.microsoft.com/en-us/library/9d0714y1(VS.80).aspx
into a file and build and test it. then chop off the parts you do not need,
modify the parts that you need (choose one of the USE_METHOD == n options
as the one you want to use and change the control/interface to your activex control).
as you want a console application with no windows, also change this (right at the end)

int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int nShowCmd)
{
   return _AtlModule.WinMain(nShowCmd);
}
vijayan121 1,152 Posting Virtuoso

for things of this kind, using a scripting language like perl would be much easier than programming it in c++.

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

const string choice_letters = "abcde" ;
const string answer_prefix = "ANS:" ;

inline bool is_choice( const string& str )
{
  return str.find_first_of( choice_letters ) == 0 &&
         str.find_first_of( '.' ) == 1 ;
}

inline bool is_answer( const string& str )
{ return str.find( answer_prefix , 0 ) == 0 ; }

int main()
{
  ifstream fin( "q_and_a.txt" ) ;
  ofstream fout("q_and_a.new.txt") ;
  string line ;
  string question ;
  vector<string> choices ;
  const ctype<char>& ct =
      use_facet< ctype<char> >( fin.getloc() ) ;
  
  while( getline( fin, line ) )
  {
    if( is_choice(line) ) choices.push_back(line) ;
    else if( is_answer(line) )
    {
      string ans ;
      size_t i = answer_prefix.size() ;
      for( ; i<line.size() ; ++i )
        if( !ct.is( ctype_base::space, line[i] ) )
            ans += ct.tolower( line[i] ) ;
      fout << question ;
      for( size_t i=0 ; i<choices.size() ; ++i )
      {
        if( ans.find_first_of( choices[i][0] ) != string::npos )
           fout << '*' ;
        fout << choices[i] << '\n' ;
      }
      question = "" ;
      choices.clear() ;
      ans = "" ;
    }
    else question += line + '\n' ;
  }
}
Salem commented: That wasn't help, that was just big-time spoon-feeding a complete answer. -2
n.aggel commented: Oh my god...! you learn a greal of things just be reading vijayan's code snipsets! +2
vijayan121 1,152 Posting Virtuoso

> pMP->GetMapID();
> Am I missing something in above function call? Or do I need to call the function differently?
no. you would have got a compile time error otherwise.

> While executing it, program is quitting with "Abnormal program termination".
try this

try
{
  pMP->GetMapID() ;
}
catch( const _com_error& ce )
{
  std::wcout << L"com error: " << ce.Description() << std::endl ;
}
catch( ... )
{
  std::cout << "some other error" << std::endl ;
}

if the error is a 'com error', look at what the error description is.

if the error is 'some other error', run the program in the visual studio debugger.
it will tell you what is the cause of the abnormal termination.
most likely, it would be an access violation.
the probable reason then is that you are accessing the object after a call to
either Release() or CoUninitialize().

vijayan121 1,152 Posting Virtuoso

check this library out. http://code.jellycan.com/simpleini/
i've not used it; but the reports that i've come across are good.
and the license is non-viral (MIT)

jaepi commented: uh huh! +2
vijayan121 1,152 Posting Virtuoso

see http://www.informit.com/articles/article.aspx?p=169524&seqNum=8&rl=1
googling would get you many more such links.

vijayan121 1,152 Posting Virtuoso

> How do you know so much about iterators, anyways? You must need to use them all the time
a c++ programmer would use iterators extensively. and so gets to be quite familiar with them.

vijayan121 1,152 Posting Virtuoso

if the iterator is a random_access iterator one + 1 is supported.
if not, you could write

for( iterator_type one ; /*...*/)
{
       iterator_type two = one ;
       for( ++two ; /*...*/)
       {
/*...*/
        }
}

if you want to figure out what kind of iterator it is, use std::iterator_traits<>. for example

#include <iterator>
#include <iostream>
#include <vector>
#include <list>
using namespace std ;

template< typename iterator_type > inline
void bar( iterator_type iterator, random_access_iterator_tag )
{ cout << "random access iterator!\n" ; }

template< typename iterator_type > inline
void bar( iterator_type iterator, bidirectional_iterator_tag )
{ cout << "bidirectional iterator!\n" ; }
// etc

template< typename iterator_type >
inline void foo( iterator_type iterator )
{
  bar( iterator,
   typename iterator_traits<iterator_type>::iterator_category()
   ) ;
}

int main()
{
  vector<int> vec ;
  list<int> lst ;
  cout << "vector<int>::reverse_iterator: " ; 
  foo( vec.rbegin() ) ;
  cout << "list<int>::iterator: " ; 
  foo( lst.begin() ) ;
}
vijayan121 1,152 Posting Virtuoso

there is nothing wrong with the mmap.ocx file.
i have been able to #import the file and build it without errors.
note: i am NOT using precompiled headers.

however, it appears that the file is licensed, and so i get a
run-time error 'Class is not licensed for use' when i try to instantiate it.
i suppose that you have the license key with you, and you would be
able to instantiate it.

#include <iostream>
#include <windows.h>

#import "C:\\cygwin\\home\\projects\\ocx_read\\mmap_read\\MMap.ocx"  \
  no_namespace no_smart_pointers raw_native_types named_guids

int main()
{
  CoInitialize(0) ;
  {
      _DMMap* pmmap = 0 ;
      HRESULT hr = CoCreateInstance( CLSID_MMap, 0, 
                       CLSCTX_ALL,  DIID__DMMap,
                       reinterpret_cast<void**>(&pmmap) ) ;
      if( SUCCEEDED(hr) )
      {
         std::cout << "succeeded in creating an instance "
                     "of mmap\n" ;
         pmmap->Release() ;
      }
      else
      {
         char strerror[128] ;
         FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM,
                  0, hr, 0, strerror, sizeof(strerror), 0 ) ;
         std::cout << "error: " << strerror ;
      }
  }
  CoUninitialize() ;
}
/***
output:
error: Class is not licensed for use
*/
vijayan121 1,152 Posting Virtuoso

you must assign static ip addresses to the two machines from one of these three non-routing address pools
192.168.0.0
to 192.168.255.255
172.16.0.0 to 172.31.255.255
10.0.0.0 to 10.255.255.255
see http://www.faqs.org/rfcs/rfc1918.html
once you have done that, use any file transfer mechanism that catches your fancy; FTP, sockets programming, NFS or whatever else. for an example see http://www.5starsupport.com/tutorial/networking-crossover-cable.htm

vijayan121 1,152 Posting Virtuoso

> C:\mmap-nov-16\Radar\Radar.cpp(8) : error C2017: illegal escape sequence
this is the first error reported by the compiler. what is this Radar.cpp file? and what does it contain? in paticular what does line 8 look like?
i repeat: create a small project which contains only a main.cpp. with only these 16 lines of code

#include <cassert>
#include<windows.h>
#import "c:\WINNT\system32\MMap.ocx" named_guids 
using namespace MMAPLib;

void main()
{
   CoInitialize( 0 );
   _DMMap* pMap = 0;

  HRESULT hr = CoCreateInstance(CLSID_MMap, 0, CLSCTX_ALL,
                DIID__DMMap,reinterpret_cast <void**>(&pMap));
  assert(SUCCEEDED(hr));
  pMap->Release();
  CoUninitialize();
}

and post the results.
also rename mmap.ocx as mmap.ocx.txt and upload that too. (click on the 'Manage Attachments' button)

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

using protected access specifier

#include <iostream>

class Rectangle
{
  protected:
      double base; // derived class members can access 
      double height; // inherited base, height 
  public:
      Rectangle( double base = 5.00, double height = 4.00 );
      // added const specifiers for selectors
      double Area() const ;
      void Display() const ;
};

Rectangle::Rectangle( double b, double h ) { base=b ; height=h ; }

double Rectangle::Area() const { return base * height ; }

void Rectangle::Display() const
{
    std::cout << "\nBase:      " << base  ;
    std::cout << "\nHeight:    " << height;
    std::cout << "\nArea:      " << Area() << '\n' ;
}


class Square : public Rectangle // use inherited base, height
{
  public: 
      Square( double base = 3.00 );
      void Display() const ;
};

Square::Square( double b ) { base=b ; height=b ; }

void Square::Display() const
{
    std::cout << "\nBase:      " << base  ;
    std::cout << "\nArea:      " << Area() << '\n' ;
}


int main()
{
    Rectangle rect1( 7.00000, 9.00000 );
    Rectangle rect2;
    Square squA;
    Square squB( 5.50 );
    std::cout << std::fixed << std::showpoint ;
    std::cout << "\nrect1\n-----" ; rect1.Display();
    std::cout << "\nrect2\n-----" ; rect2.Display();
    std::cout << "\nsquA\n-----" ; squA.Display();
    std::cout << "\nsquB\n-----" ; squB.Display();
}

> Is there a way to use the same display() for both classes?
there is.

#include <iostream>
#include <cmath>

class Rectangle
{
  private:
      double base;
      double height;
  public:
      Rectangle( double base = 5.00, double height = 4.00 );
      double Area() const ;
      void Display() const ;
};

// using initializer list …
vijayan121 1,152 Posting Virtuoso
class Rectangle  //class declaration
{
  protected: // look up [B]protected[/B] in your text book  
      double base;
      double height;
  public:
      Rectangle(double base = 5.00, double height = 4.00); //constructor
      double area();
      void display();
};

> How do I not hide Rectangle::base, Rectangle::height in Square?
by not declaring members with the same name in Square

vijayan121 1,152 Posting Virtuoso

consider not hiding Rectangle::base, Rectangle::height in Square.
hint: like public and private, you also have a protected access specifier.

vijayan121 1,152 Posting Virtuoso

first do this. create a small project which contains only a main.cpp as follows.

#include <cassert>
#include<windows.h>
#import "c:\WINNT\system32\MMap.ocx" named_guids 
using namespace MMAPLib;

void main()
{
   CoInitialize( 0 );
   _DMMap* pMap = 0;

  HRESULT hr = CoCreateInstance(CLSID_MMap, 0, CLSCTX_ALL,
                DIID__DMMap,reinterpret_cast <void**>(&pMap));
  assert(SUCCEEDED(hr));
  pMap->Release();
  CoUninitialize();
}

does this compile and link without errors?
if no, post the complete error message(s) generated by the compiler/linker and the complete .tlh file that was generated.
if yes, run the program. does it run without errors?

vijayan121 1,152 Posting Virtuoso

> I can't get my display() method to work properly in the derived class. The function calls within it keep reading the dimensions from the original Rectangle class. Isn't there a way I can "virtualize" something and get the inner functions to read the right data?

class Rectangle		//class declaration
{
private:
    double base;
    double height;
public:
    Rectangle(double base = 5.00, double height = 4.00);    //constructor
    double area();
    void display();
};
// ....
double Rectangle::area()
{
    double a;
    a = (base * height);
    [B]// really means a = Rectangle::base*Rectangle::height ;[/B]
    return a;
}
// ....
class Square : public Rectangle	//class declaration
{
private:
    double base;[B] // hides Rectangle::base[/B]
    double height;[B] // hides Rectangle::height[/B]
public:
    Square(double base = 3.00);	//constructor
    void display();
};
// ...
Square::Square(double b)
{
    base = b;  [B]// means Square::base = b [/B];
    height = b; [B]// means Square::height = b ;[/B]
   [B] // Rectangle::base, Rectangle::height are  initialized 
   // by the default constructor of Rectangle to 5.00, 4.00[/B]
}
// ....
void Square::display()
{
    cout << "\nBase:      " << base;
    cout << "\narea:      " << Square::area();  //tried a bunch of things here
    [B]// Square::area() is the inherited Recatngle::area()
   // which returns Rectangle::base*Rectangle::height ;
   // ie. 5.00 * 4.00[/B]
}

you should now be able to figure out what the problem is. and what you should do to address it.

vijayan121 1,152 Posting Virtuoso
#include <sstream>
#include <string>
#include <iostream>

template< typename T > inline std::string to_string( const T& v )
{
  std::ostringstream stm ;
  return (stm << v) ? stm.str() : "error" ;
}

int main()
{
  double value = 1.2345 ;
  std::string str_value = to_string(value) ;

  // c++0x
  // std::string str_value = lexical_cast<std::string>(value) ; 

  std::cout << value << '\t' << str_value << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

looks like you are compiling with the /Yu"stdafx.h" compiler option. new projects in Visual C++ set this option by default to increase compilation speed. (to change the option, use the Project.Settings.C++.Precompiled Headers dialog.)

the Visual C++ Programmer's Guide explains the behavior you see:

"The compiler treats all code occurring before the .h file as precompiled. It skips to just beyond the #include directive associated with the .h file, uses the code contained in the .pch file, and then compiles all code after filename.."

http://msdn2.microsoft.com/en-us/library/z0atkd6c(VS.71).aspx
this means, everything in your code file before the #include "stdafx.h" line is completely ignored, because the compiler assumes that the necessary information is in your precompiled header.

you can fix the problem by one of these ways
a. move the #import directive and the using namespace directive after the other #include statements. in particular #include "stdafx.h"
b. move the #import directive and the using namespace directive into stdafx.h
c. turn off precompiled headers option (set it to not using precompiled headers)

then clean (or delete the .pch file) and rebuild you project.

vijayan121 1,152 Posting Virtuoso

the generated header file that you posted contains

#pragma once
#pragma pack(push, 8)

#include <comdef.h>

namespace MMAPLib {
// ...
} // namespace MMAPLib

and your #import is

#import "c:\WINNT\system32\MMap.ocx" \
named_guids LIBID_MMAPLib,DIID_DMMap,DIID_DMMapEvents,CLSID_MMap \
no_namespace MMAPLib

these are not consistent with each other (no_namespace => do not generate a namespace)

you need to recompile your code after making any modification to the #import to get the
newly generated header file. i suspect you have not done that.

if (and only if) your header generates definitions inside namespace MMAPLib { add a using namespace MMAPLib; directive right after the #import
then either of these should work

CoCreateInstance(     CLSID_MMap,
                       0,
                       CLSCTX_ALL,
                       DIID__DMMap,
                       reinterpret_cast <void**>(&pMP) );

or

CoCreateInstance(     __uuidof( MMap ),
                       0,
                       CLSCTX_ALL,
                       __uuidof( _DMMap ),
                       reinterpret_cast <void**>(&pMP) );
vijayan121 1,152 Posting Virtuoso

> But while compiling error is getting errors like 'MMap' :undeclared identifier
looks like you have not used the no_namespace attribute; so the identifiers are in a namespace in the .tlh
also looks like you have not read my previous post or if you have read it, you haven't understood it.

in any case, to avoid getting into what in programming would be called an infinite loop, post the entire contents of the generated .tlh file. also the actual #import statement that you used.
on second thoughts, don't post it; just attach it to your post as a plain text file. that way, we would not have to contend with the intricacies of using code tags and the perversities indulged in by aniweb's code formatter and the preview facility provided.

vijayan121 1,152 Posting Virtuoso

> How did you define "IID_IiTunesDetector" variable in your header file?
it was defined for me in the generated .tlh header due to the presence
of the named_guids attribute in the #import directive

this is (an extract from) the .tlh header generated:

// ...
// Forward references and typedefs
struct __declspec(uuid("d6995525-b33a-4980-a106-9df58570cc66"))
/* LIBID */ __ITDETECTORLib;
struct /* coclass */ iTunesDetector;
struct __declspec(uuid("45d2c838-0137-4e6a-aa3b-d39b4a1a1a28"))
/* dual interface */ IiTunesDetector;

// Type library items
struct __declspec(uuid("d719897a-b07a-4c0c-aea9-9b663a28dfcb"))
iTunesDetector;
    // [ default ] interface IiTunesDetector

struct __declspec(uuid("45d2c838-0137-4e6a-aa3b-d39b4a1a1a28"))
IiTunesDetector : IDispatch
{
    // Raw methods provided by interface
    // ...
      virtual HRESULT __stdcall get_iTunesVersion (
        /*[out,retval]*/ long * pVal ) = 0;
    // ...
};

// Named GUID constants initializations
extern "C" const GUID __declspec(selectany) LIBID_ITDETECTORLib =
    {0xd6995525,0xb33a,0x4980,{0xa1,0x06,0x9d,0xf5,0x85,0x70,0xcc,0x66}};
extern "C" const GUID __declspec(selectany) CLSID_iTunesDetector =
    {0xd719897a,0xb07a,0x4c0c,{0xae,0xa9,0x9b,0x66,0x3a,0x28,0xdf,0xcb}};
extern "C" const GUID __declspec(selectany) IID_IiTunesDetector =
    {0x45d2c838,0x0137,0x4e6a,{0xaa,0x3b,0xd3,0x9b,0x4a,0x1a,0x1a,0x28}};
// ...

so i could use the named constants as in

CoCreateInstance( CLSID_iTunesDetector, 0, 
                    CLSCTX_ALL,
                    IID_IiTunesDetector,
                    reinterpret_cast<void**>(&pitd) ) ;

alternatively i could have written

CoCreateInstance( __uuidof(iTunesDetector), 0, 
                    CLSCTX_ALL,
                    __uuidof(IiTunesDetector),
                    reinterpret_cast<void**>(&pitd) ) ;

this would not require generation of named guid constants.

if you want to generate named guid constants, use named_guids attribute in the #import directive

#import "c:\WINNT\system32\mmap.ocx" named_guids no_namespace

without the no_namespace attribute for the #import,
all names imported would be inside a namespace (with the base name of the typelib).

or else use the __uuidof operator
in your case the uuid for the interface would be given by __uuidof( …

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

this article should contain all the information that you need: http://www.ddj.com/cpp/184403638;jsessionid=S0L5ADAGUG4VKQSNDLRSKH0CJUNN2JVN?pgno=4 take note of the date it was written; the references to Microsoft C++ are to the now obsolete VC++ 6.0 and not to the current 8.0 version, which has a complete rewrite of the standard c++ library (based on Dinkumware).

vijayan121 1,152 Posting Virtuoso

> getting managed code to talk to unmanaged code?
the easy way is to just mix the managed and unmanaged code as required.
this is called IJW ( "it just works" ). using p-invoke is only slightly harder.

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace System;
using namespace std ;

#pragma unmanaged
void sort_and_print( int* p, size_t N ) 
{
  std::sort( p, p+N ) ;
  std::copy( p, p+N, ostream_iterator<int>(cout,"\n") ) ;
}

#pragma managed
int main( array<System::String ^> ^args )
{
    enum { SIZE = 100 };
    array<int>^ a = gcnew array<int>(SIZE);
    System::Random^ rg = gcnew System::Random() ;
    for( int i=0 ; i<SIZE; ++i ) a[i] = rg->Next( 500, 1000 ) ;

    // pin the array (don't let the gc move it around).
    pin_ptr<int> pinned_address = &( a[0] ) ;   
    int* cpp_pointer = pinned_address ;
    sort_and_print( cpp_pointer, SIZE ) ;
}
vijayan121 1,152 Posting Virtuoso

> ...some simple sample code related to this

#include <iostream>
#include <windows.h>
#include <cassert>

// disable a whole bunch of unnecessary (for me) stuff  by no_*
#import "C:\\Program Files\\iTunes\\ITDetector.ocx"  \
        no_namespace no_smart_pointers raw_interfaces_only \
        raw_native_types no_implementation named_guids

int main()
{
  CoInitialize(0) ;
  {
      IiTunesDetector* pitd = 0 ;
      // CLSID_iTunesDetector, IID_IiTunesDetector are 
      // picked up from itdetector.tlh (named_guids)
      HRESULT hr = CoCreateInstance( CLSID_iTunesDetector,
                    0, 
                    CLSCTX_ALL,
                    IID_IiTunesDetector, // interface uuid 
                    reinterpret_cast<void**>(&pitd) ) ;
      assert( SUCCEEDED(hr) ) ;
      
      
      // iTunesVersion is a property (raw_interfaces_only)
      long version = 0 ;
      hr = pitd->get_iTunesVersion( &version ) ;
      assert( SUCCEEDED(hr) ) ;
      std::cout << "iTunes version is " << std::hex 
               << std::showbase << version << '\n' ;
      
      pitd->Release() ;
  }
  CoUninitialize() ;
}
vijayan121 1,152 Posting Virtuoso

i think you misunderstood what i meant. let me clarify. there are constructs which are clearly C++, there are others which are clearly C (and not C++). and there are many which could be either. i suggest that in these cases we should assume that the person who posed the question knows best what language he/she is programming in. for example, if someone has issues with dynamically resized arrays, suggesting the use of a std::vector instead is possible in C++, not in C.
i see now that WaltP had already pointed this out earlier; i must have missed his post while replying.

vijayan121 1,152 Posting Virtuoso

> This should have never compiled in gcc ...
true, it should never compile without errors in any c++ compiler.
but g++ does accept it without specific switches that turn on C++ compliance.
eg. > g++ --std=c++98 --pedantic -c whatever.cc
or > g++ --ansi --pedantic -c whatever.cc
would generate the error.

vijayan121 1,152 Posting Virtuoso

> When I clear the map, the memory stays allocated to my program, but when I clear the vector it is returned to the OS immediately.
the vector allocation is for one large contiguous chunk of memory, the map makes many allocations of small chunks of memory. the allocator behaviour could be different in each case. (the behaviour varies depending on the implementation: microsoft's heap api on windows, dlmalloc used by gnu and either phkmalloc or jemalloc on bsd)

> Is there any way to tell it to give the memory back to the OS?
with the standard c++ library, implementing a custom allocator is the canonical way of specifying memory management policy. as the map has a large number of allocation and deallocation of small objects, a pool allocator could be used. one implementation is available in http://www.boost.org/libs/pool/doc/index.html

vijayan121 1,152 Posting Virtuoso

you could use a std::set< std::string > ( or a map or a hashmap as you suggested ) to check for the duplicates. see this thread: http://www.daniweb.com/forums/thread81348.html

vijayan121 1,152 Posting Virtuoso

> The OP rarely has an idea how to cut and paste your code into his project and have it work.
my idea was not to have the OP cut and paste my code. merely that it should give him a pointer in the right direction.

vijayan121 1,152 Posting Virtuoso

> Keep in mind that assert() responds to errors by improperly terminating your program and printing an error message
you do not understand assertions at all. assert is an effective way to catch programming errors during development and testing, and yet they are filtered out (easily) of production code. if errors are expected in production code, the technique is to throw an exception. and an unhandled exception also ends up (very properly) terminating your program.

> Assert() is habitually taught and/or used as an error-handling device.
> The problem with that is that its usefulness is limited to a very small domain.
assertions are not error handling devices. their usefulness is in veryfying that invariants are not violated in code, and if they are bringing it to the develpors attention. assert can not be used as an error handling device; it does not exist in production code.

> Somehow methinks Salem did a very good job of being much more succinct than I did...
true. also a lot more logical and coherent. and a lot less hysterical.

vijayan121 1,152 Posting Virtuoso

DefineDosDevice (with DDD_RAW_TARGET_PATH flag) could be used to create a junction in the object namespace; the junction can then be used as a dos path string.
http://msdn2.microsoft.com/en-us/library/aa363904.aspx

if the device already has a dos name, QueryDosDevice can be used to get information about dos device names. http://msdn2.microsoft.com/en-us/library/aa365461.aspx

vijayan121 1,152 Posting Virtuoso

you still use RegQueryValueEx.

LONG WINAPI RegQueryValueEx( HKEY hKey, LPCTSTR lpValueName, 
            LPDWORD lpReserved,
            LPDWORD lpType, // will be set to the type of data 
                  // (eg. REG_BINARY if value was binary) 
            LPBYTE lpData, LPDWORD lpcbData );

see http://msdn2.microsoft.com/en-us/library/ms724884.aspx for the registry value types.

Ramy Mahrous commented: well done +7
vijayan121 1,152 Posting Virtuoso

> It is also a terrible use of assert ....
> ... user input should be guarded with if statements to check for validity, not asserts

you are absolutely right, that was a terrible use of assert. hopefully, you put that in before johnpmii had a chance to read my earlier post. thanks, salem.

vijayan121 1,152 Posting Virtuoso
// ...
switch (response){
  case 'a':
  case 'A':
    cout << "How many numbers do you want to enter?" << endl;
    cin >> num;
    cout << "Start entering numbers." << endl;
    cin >> newNumber ;
    max = newNumber ; 
    for (int count = 1; count < num; count++){
      cin >> newNumber;
      max = larger( max, newNumber ) ;
    }
    cout << "The largest number is: " << max << endl;
    break;
  case 'b':
  case 'B':
    cout << "Start entering numbers. -99 to quit" << endl;
    cin >> newNumber ;
    min = newNumber ; 
    while ( ( cin >> newNumber) && (newNumber != -99)){
        max = smaller( min, newNumber ) ; 			   
    };
    cout << "The smallest number is: " << min << endl;
    break;
// ...
vijayan121 1,152 Posting Virtuoso

something like this perhaps?

#include <iostream>

inline int larger( int a, int b ) { return a>b ? a : b ; }
inline int smaller( int a, int b ) { return a<b ? a : b ; }

int main()
{
  int number ;
  std::cin >> number ;
  int largest = number, smallest = number ;
  while( (std::cin>>number) && (number!=-99) )
  {
    largest = larger( largest, number ) ;
    smallest = smaller( smallest, number ) ;
  }
  std::cout << "largest: " << largest
      << "  smallest: " << smallest << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

...
I have a couple of quick questions.
I'm new to the c++ programming and I do not total understand how the command: assert( getline( file, str1, ':' ) ) ; works?
Does the ':' tell the getline where to stop and what does the "assert command do? I tried using it and it gave me an error and I had to take it out. I was still able to use the info you gave me and get my functions to work in the main part of my program.

- via PM

assert is a macro (defined in the header <cassert>). what assert does is simple: assert(e): if the int expression e is evaluates to zero (false), a diagnostic message is written to stderr that includes:
a. the text of the expression e
b. the source filename (__FILE__)
c. the source line number (__LINE__)
and then calls abort.

assertions are typically used to verify that assumptions that the programmer has made while writing code hold at runtime. and if they do not, they make sure that you hear the bad news.
see http://en.wikipedia.org/wiki/Assertion_(computing) and
http://www.cprogramming.com/tips/showTip.php?tip=55&count=30&page=0

// get first letter after the first colon
assert( geline( file, str2, ':' ) && !str2.empty() ) ;

check that the call to getline succeeded and that the string str2 contains at least one char; if this is not the case, let me know immediately (fail loudly).
note: this …

vijayan121 1,152 Posting Virtuoso

> you should have posted this in the C forum. There is nothing specific to C++ in this thread.
do you really mean

namespace { int foobar( int i ) { return ++i ; } }

is c++, but if you place the same function in the global namespace, it suddenly stops being c++?