vijayan121 1,152 Posting Virtuoso

sort before inserting the string into the multimap?

void fill_mmap( std::multimap< std::string, int >& mmap,
                std::ifstream& file )
{
  std::string line ;
  for( int line_num = 1 ; std::getline( file, line ) ; ++line_num )
  {
    std::sort( line.begin(), line.end() ) ;
    mmap.insert( std::make_pair( line, line_num ) ) ;
  }
}
vijayan121 1,152 Posting Virtuoso

> Do you know how you would go about finding the length of an array?
the array 'decays' into to a pointer when you pass it to a function.
also pass the size of the array (as a second parameter) to the function:

void clearCharArray( char arrayToClear[], std::size_t size )
// ...
testVar.clearCharArray( testVar.harvest, sizeof(testVar.harvest) );

why not you use a std::vector<char> instead?

vijayan121 1,152 Posting Virtuoso

> Is there anything that 'wraps' pipes?
i do not know of any, but it is very easy to roll out one of our own. eg.

#include <stdio.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
using namespace boost::iostreams ;

struct opipestream : stream< file_descriptor_sink >
{
  typedef stream< file_descriptor_sink > base ;
  explicit opipestream( const char* command )
    : base( fileno( pipe = popen( command, "w" ) ) ) {}
  ~opipestream() { close() ; pclose( pipe ) ; }
  private : FILE* pipe ;
};

int main()
{
  std::cout << "#includes in this file:" << std::flush ;
  std::ifstream fin( __FILE__ ) ;
  opipestream pout( "grep '^#include' | wc -l" ) ;
  pout << fin.rdbuf() ;
}

// link with libboost_iostreams  eg.
// g++ -Wall -std=c++98 -pedantic -I /usr/local/include -L /usr/local/lib -lboost_iostreams myfile.cc
vijayan121 1,152 Posting Virtuoso
void clearCharArray( char arrayToClear[] )
{
  int arrayLength = 0;

  // Get the length of the array passed
  // this will not give you the length of the array passed
  arrayLength = sizeof( arrayToClear );
  // equivalent to arrayLength = sizeof( char* ) ;

  for( int i = 0; i < arrayLength; i++ )
  {
    if( arrayToClear[i] != 0 )
    {
        arrayToClear[i] = 0;
    }
  }
}
vijayan121 1,152 Posting Virtuoso
#include <algorithm>

class LakeDataClass
{
  public:
    char DTG[13];
    float DepthOfMeasurements;
    char WaveDirectionStrength[5];
    char Weather[9];
    float DissolvedOxygen;
    float pH;
    float AirTempCelsius;
    float WaterTempCelsius;
    float WaterTempFahrenheit;
    float AirTempFahrenheit;
    float SunLight;
    float BarPress;
};

bool compare_on_descending_value( const LakeDataClass& first,
                                  const LakeDataClass& second);

// can't modify const things! remove the const specifier
void sort_on_descending_value( /*const*/ LakeDataClass* array, int N );


int main()
{
  const int MAXSZ = 1000 ;
  LakeDataClass LakeDataArray[MAXSZ] ;
  int ObjectReadCount = 0 ;

  // fill up array here
  // increment ObjectReadCount for each object read

  // to sort the array:
  sort_on_descending_value( LakeDataArray, ObjectReadCount ) ;
  // use sorted array
}

bool compare_on_descending_value( const LakeDataClass& first,
                                  const LakeDataClass& second )
{
  return first.pH > second.pH;
}


void sort_on_descending_value( /*const*/ LakeDataClass* array, int N )
{
   std::sort ( array, array+N, compare_on_descending_value );
}

> attempts to sort on the character array DTG failed .,..
write the comparison function this way:

#include <cstring>
bool compare_on_asscending_value( const LakeDataClass& first,
                                  const LakeDataClass& second )
{
  return std::strcmp( first.DTG, second.DTG ) < 0 ;
}
vijayan121 1,152 Posting Virtuoso

dragon: > You might also be able to do this with templates
yes, if there are a lot of members, templates would provide a generic mechanism.
didn't post this earlier because i didn't want to scare away the OP (having spent some time here, i'm a little wiser now) .

#include <functional>

// compare member variable of type T (class C)
template< typename C, typename T >
struct cmp_mem_var_t : std::binary_function<C,C,bool>
{
  cmp_mem_var_t( T C::*p_mem_var, bool ascend )
    : ptr_mem_var(p_mem_var), ascending(ascend) {}
  bool operator() ( const C& first, const C& second ) const
  {
    return ascending ?
             first.*ptr_mem_var < second.*ptr_mem_var :
             first.*ptr_mem_var > second.*ptr_mem_var ;
  }
  private:
    T C::*ptr_mem_var ;
    bool ascending ;
};

// compare result (type T) of a const member function (class C)
template< typename C, typename T >
struct cmp_mem_fun_t : std::binary_function<C,C,bool>
{
  cmp_mem_fun_t( T (C::*p_mem_fun)() const, bool ascend )
    : ptr_mem_fun(p_mem_fun), ascending(ascend) {}
  bool operator() ( const C& first, const C& second ) const
  {
    return ascending ?
             (first.*ptr_mem_fun)() < (second.*ptr_mem_fun)() :
             (first.*ptr_mem_fun)() > (second.*ptr_mem_fun)() ;
  }
  private:
    T (C::*ptr_mem_fun)() const ;
    bool ascending ;
};

// two helpers to deduce types (syntactic sugar)
template< typename C, typename T > inline cmp_mem_var_t<C,T>
compare_member( T C::*p_mem_var, bool ascending = true )
{ return cmp_mem_var_t<C,T>( p_mem_var, ascending ) ; }

template< typename C, typename T > inline cmp_mem_fun_t<C,T>
compare_member( T (C::*p_mem_fun)() const, bool ascending = true )
{ return cmp_mem_fun_t<C,T>( p_mem_fun, ascending ) ; }

and this is how it could be used:


       
vijayan121 1,152 Posting Virtuoso

> I find it interesting that the resolution implied by CLOCKS_PER_SEC is 1/1000000 second,
> but my actual results show 1/100 second.
how typical of linsux. appearances are more important than technical accuracy.
the reason for this dishonesty:

STANDARDS
     The clock() function conforms to ISO/IEC 9899:1990 (``ISO C90'').  How-
     ever, Version 2 of the Single UNIX Specification (``SUSv2'') requires
     CLOCKS_PER_SEC to be defined as one million.  FreeBSD does not conform to
     this requirement; changing the value would introduce binary incompatibil-
     ity and one million is still inadequate on modern processors.

- FreeBSD man pages (FreeBSD reports 128 as the value of CLOCKS_PER_SEC)

however, your os would have a variety of clocks/timers, many with much higher resolution.
see: http://www.freebsdmanpage.com/man/clocks-7.html

vijayan121 1,152 Posting Virtuoso

the C library clock() does not give the wall clock:

the clock() function determines the amount of processor time used since the invocation of the calling process, measured in CLOCKS_PER_SECs of a second.

just sleeping or waiting for input will work for time() (which gives the wall time), not for clock() ; no processor time is used by the process while it is in a wait state.

Salem commented: Yes, sleeping and I/O doesn't count. +15
vijayan121 1,152 Posting Virtuoso

let's say you have a struct/class of this kind:

struct A
{
  int number ;
  double value ;
  char name[30] ;
};

and you want to sort an array of A s on the member value .
first, write a comparison function that the sort can use which accepts two A s to be compared:

bool compare_on_descending_value( const A& first, const A& second )
{
  // function to compare elements of the sequence
  // return true if first should appear *before* second
  // in the sorted sequence; false otherwise
  // for example, this would sort on descending value (member)
  return first.value > second.value ;
}

then call std::sort (header <algorithm> ) passing the comparison function to tell it how elements should be compared for the sort:

void sort_on_descending_value( A* array, std::size_t num_elements )
{
  // use std::sort from <algorithm>
  std::sort( array, array+num_elements, compare_on_descending_value ) ;
}
vijayan121 1,152 Posting Virtuoso

do not pass the address of a local variable (with automatic storage duration) to a thread function; it may not be around by the time the thread executes.

// ...
char* input_sentence = new char[32];
std::strcpy( input_sentence, "ANGLE 360" ) ;
thread = _beginthread( SerialThread, 8192, input_sentence ) ;
// ...

void SerialThread( void* input )
{

     char*  line = static_cast<char*>(input) ;
     Fmain->Memo1->Lines->Append(line);
     delete [] line ;
     _endthread();
}
vijayan121 1,152 Posting Virtuoso

ideally, do not use the (now deprecated) functionality in namespace __gnu_cxx . they have been superceded by tr1 in c++0x.
use -std=c++0x (gcc 4.3) , std::tr1 (gcc4.2) or boost::tr1 (earlier versions).

the error is because __gnu_cxx::hash<> is a struct (function object); not a function. if you have to use it, use it this way

#include <functional>
#include <ext/hash_fun.h>
using namespace std ;

template<class X, class Pred= less<X> >
class Hash{
private:
  Pred comp;
public:
  enum{bucket_size = 4, min_buckets = 8}; 
  Hash() : comp(){ }
  Hash(Pred p) : comp(p){ }
  size_t operator()(const X& x) const{
    const size_t i= __gnu_cxx::hash<X> [B]()[/B] (x);
    return 16807U*(i%127773U)+(95329304U-2836U*(i/127773U));
  }
  
};
vijayan121 1,152 Posting Virtuoso

> I'm going to research vijayan121's links to see if I can get them to work for me.
if you just need to communicate between the two processes, a file is not required at all. you could use a standard IPC technique (shared memory, pipes, sockets, rpc). a file is required only if you want the data to persist after process termination.

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

> I would like to be able to read from pipe in child so I know what parent has sent.
> How to do this ...
the simplest way would be to use read and write on the anonymous pipe.
man read(2) http://www.freebsd.org/cgi/man.cgi?query=read&apropos=0&sektion=2&manpath=FreeBSD+7.0-stable&format=html
man write(2) http://www.freebsd.org/cgi/man.cgi?query=write&apropos=0&sektion=2&manpath=FreeBSD+7.0-stable&format=html

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

int main()
{
  int toChild[2] = {0}, fromChild[2] = {0};
  pid_t pid = -1 ;
  char parent_msg[] = "*** message from parent" ;
  char child_msg[] = "### message from child" ;

  pipe(toChild) ;
  pipe(fromChild) ;
  pid = fork() ;

  if(pid == 0)
  {/* CHILD */
    close(toChild[1]); //child won't write to child... :)
    close(fromChild[0]); //child won't read it's own messages
    char buff[ sizeof(parent_msg) ];
    read( toChild[0], buff, sizeof(parent_msg) ) ;
    pid_t pid = getpid() ;
    printf( "in child (pid %d): read: %s\n", pid, buff ) ;
    write( fromChild[1], child_msg, sizeof(child_msg) ) ;
    close(toChild[0]);
    close(fromChild[1]);
  }
  else
  {/* PARENT */
    close(toChild[0]); //paren't won't read his own messages...
    close(fromChild[1]); //paren't won't write to parent... :)
    write( toChild[1], parent_msg, sizeof(parent_msg) ) ;
    char buff[ sizeof(child_msg) ];
    read( fromChild[0], buff, sizeof(child_msg) ) ;
    pid_t pid = getpid() ;
    printf( "in parent (pid %d): read: %s\n", pid, buff ) ;
    close(toChild[1]);
    close(fromChild[0]);
  }
  return 0;
}
vijayan121 1,152 Posting Virtuoso

> a different program to read from that file BEFORE the first program is finished writing to it.
the output to a file is buffered at many levels: by the fstreambuf of the c++ library and by the operating system (cache manager). to achieve coherence between the two processes' view of the file, consider memory mapping the file.
see: http://msdn2.microsoft.com/en-us/library/aa914748.aspx
and http://msdn2.microsoft.com/en-us/library/aa914405.aspx

vijayan121 1,152 Posting Virtuoso

put all the common stuff in a base class and inherit from it.

#include <iostream>

template< typename E > struct enemy_manager_base
{
  void same_for_all()
  { std::cout << "same for all enemies\n" ; }
};

template< typename E > struct enemy_manager : enemy_manager_base<E>
{
  void to_be_specialized()
  { std::cout << "generalization of to_be_specialized\n" ; }
};

struct tank ;

template<> struct enemy_manager<tank> : enemy_manager_base<tank>
{
  void to_be_specialized()
  { std::cout << "specialization of to_be_specialized (tank)\n" ; }
};

int main()
{
  enemy_manager<int> em_gen ;
  em_gen.same_for_all() ;
  em_gen.to_be_specialized() ;

  enemy_manager<tank> em_tank ;
  em_tank.same_for_all() ;
  em_tank.to_be_specialized() ;
}
vijayan121 1,152 Posting Virtuoso

> error C2514: 'food' : class has no constructors (line 15)
> see declaration of 'food' (line 7)
> is the error caused by friending MainControl with a derived class?
no.
class food has been declared, but not defined.
you need to #include "food.h"

vijayan121 1,152 Posting Virtuoso
// ...
A *b;
b = new B(param1, param2);
delete b; 
// ...

the destructor that is called in line 4 is A::~A()
you need to call B::~B() to destroy both strings
solution: the destructor for the base class must be virtual.

class A
{
public:
	string sa;
	A(string sia);
	virtual ~A() {}
};
vijayan121 1,152 Posting Virtuoso
class objects;
class food;
class MainControl
{
  public:
  friend class objects;
  friend class food;
  // ...
};
vijayan121 1,152 Posting Virtuoso

non-static member functions have an implicit argument: the this pointer (a pointer to the object the function is called on). a pointer to a free function has nothing of this kind. the dereference operators on pointers to members ( .* and ->* ) are binary operators; you dereference a pointer to a member with respect to an object on which the member is applied. it is best to think of pointers to members as opaque abstractions that aren't really pointers (in the C sense).

the usual work around is something like this:

class Testing
{
  private:
    cLog* m_Log;
    pthread_t tid; // would one suffice?
    // std::vector<pthread_t> tids ; ?

    public:
      Testing( );
      ~Testing( );
      void floodLog( int nThreads );

    private:
      void* writeToLog( void* );
      
      static void* thread_fun( void* args ) ;

      struct thread_fun_args
      {
        Testing* This ;
        // other args as required; in this case
        void* actual_arg ;
        thread_fun_args( Testing* t, void* p ) 
            : This(t), actual_arg(p) {}
      };
};

void Testing::floodLog( int nThreads )
{
  cout << "Flooding cLog class with " << nThreads << " threads.\n";
  for( int i = 0; i < nThreads; i++ )
  {
    cout << "Created Thread: " << ( i + 1 ) << endl;
    pthread_create( &tid, NULL, &Testing::thread_fun, 
                            new thread_fun_args(this,0) );
  }
  cout << "Finished flooding.\n";
}

void* Testing::thread_fun( void* pv )
{
    thread_fun_args* tf_args = static_cast<thread_fun_args*>(pv) ;
    Testing* This = tf_args->This ;
    void* args = tf_args->actual_arg ;
    void* result = This->writeToLog( args ) ;
    delete tf_args ;
    return result …
vijayan121 1,152 Posting Virtuoso

Form::ShowDialog() shows the form as a modal dialog box. (the code following it is not executed until after the dialog box is closed.)
to show two instances of the same form:
a. create two instances of the Form (you seem to already have one instance, so create one more)
b. call Form::Show() on each of them.

vijayan121 1,152 Posting Virtuoso

> what is the problem
the problem is that string b; creates an empty string. b[j]=a[i]; is incorrect; there are no characters in b.

> i want the first character on string a to be the last char on string b
> up until the last on a is the first on b
this would suffice.

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

int main()
{
  string a;
  cout<< "enter string" <<endl;
  cin>> a;

  string b( a.rbegin(), a.rend() ) ;
  cout<< b <<endl;
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

if you want to iterate through a sequence container erasing elements as you go along, you must use the return value of container::erase . the return value is a vald iterator that designates the first element remaining beyond element(s) erased, or end if no such element exists. for example, the following will erase all even numbers from the vector.

std::vector<int> vec(100) ;
  for( int i=0 ; i<vec.size() ; ++i ) vec[i] = i ;
  std::vector<int>::iterator iter = vec.begin() ; 
  while( iter != vec.end()  )
  {
    if( ( *iter % 2 ) == 0 ) iter = vec.erase( iter ) ;
    else ++iter ;
  }

to remove duplicate elements that are adjacent to each other in a specified range, you can use the algorithm std::unique . for example, this will erase adjacent duplicate elements from the vector.

std::vector<int> vec(100) ;
  for( int i=0 ; i<vec.size() ; ++i ) vec[i] = i/10 ;
  vec.erase( std::unique( vec.begin(), vec.end() ), vec.end() ) ;
Ancient Dragon commented: Gread explaination -- I learned something too today :) +25
vijayan121 1,152 Posting Virtuoso
// ...   
   val = 0;
   for (p=0; p<3; p++)
  {
      //val += (a[i][p]*b[p][i]);
      val += (a[i][p]*b[p][j]);
      cout << a[i][p] << " x " << b[p][j] << " + ";
   }
   // ...
vijayan121 1,152 Posting Virtuoso

> do you know of any good books or sites that extensively cover WIN32 API odd ball type code
i don't program very much in the win32 environment. the only one i can think of on the spur of the moment is sysinternals
http://forum.sysinternals.com/forum_topics.asp?FID=9
there would be many others which i am not aware of.

> I am in need of an advance C++ code reference? Advance being the key word.
do you mean as a language/library reference? if it is *one* book you are looking for, i don't think that Stroustrup's The C++ Programming Language (Special Edition) can be bettered. a c++ programmer can use this as a reference. It is also a pretty good tutorial (if you are not a beginner).
if you were looking for more than one book, these are some of the the books (which come to mind right now) that i've liked.
1. Ruminations on C++: A Decade of Programming Insight and Experience by Andrew Koenig, Barbara E. Moo
2. The Design and Evolution of C++ by Bjarne Stroustrup
3. Advanced C++ Programming Styles and Idioms by James O. Coplien
4. Inside the C++ Object Model by Stanley B. Lippman
5. C++ Templates: The Complete Guide by David Vandevoorde, Nicolai M. Josuttis
6. Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu
7. C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond by David Abrahams, …

vijayan121 1,152 Posting Virtuoso

this is what Pietrek suggests:

#define _WIN32_WINNT  0x0501
#define NO_STRICT
#include <windows.h>
#include <winternl.h>
#include <iostream>
#include <cassert>

wchar_t*  GetEnvironmentStringsW( HANDLE  hproc )
{
  void* p_ntdll = GetModuleHandle( L"ntdll.dll" ) ;
  typedef NTSTATUS (__stdcall* tfn_qip ) ( HANDLE,
                    PROCESSINFOCLASS, void*, ULONG, PULONG ) ;
  tfn_qip pfn_qip = tfn_qip( GetProcAddress( p_ntdll, 
                     "NtQueryInformationProcess" ) ) ;
  assert( pfn_qip ) ;
  PROCESS_BASIC_INFORMATION pbi ;
  ULONG res_len = 0 ;
  NTSTATUS status = pfn_qip( hproc,  ProcessBasicInformation,
                     &pbi, sizeof(pbi), &res_len ) ;
  assert( res_len == sizeof(pbi) ) ;
  size_t ppeb = size_t( pbi.PebBaseAddress ) ;

  char peb[ sizeof(PEB) ] ;
  DWORD read ;
  ReadProcessMemory( hproc, pbi.PebBaseAddress, 
                           peb, sizeof(peb), &read ) ; 
  assert( read == sizeof(peb) ) ;

  enum { OFFSET_PEB = 0x10, OFFSET_X = 0x48 };
  
  void* ptr = (void*) *(INT_PTR*)(peb + OFFSET_PEB ) ;
  char buffer[ OFFSET_X + sizeof(void*) ] ;
  ReadProcessMemory( hproc, ptr, buffer, sizeof(buffer), &read ) ; 
  assert( read == sizeof(buffer) ) ;
  
  void* penv = (void*) *(INT_PTR*)( buffer + OFFSET_X ) ;
  enum { MAX_ENV_SIZE = 4096 }; 
  wchar_t* env = new wchar_t[ MAX_ENV_SIZE ] ;
  ReadProcessMemory( hproc, penv, env, MAX_ENV_SIZE, &read ) ; 
  assert( read > 0 ) ;
  
  return env ;
}

// small test driver
int main()
{
  HWND hwnd = FindWindow( 0, L"Solitaire" ) ;
  assert( hwnd ) ;
  DWORD procid = 0 ;
  GetWindowThreadProcessId( hwnd, &procid ) ;
  assert( procid ) ;
  DWORD amask = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ ;
  HANDLE hproc = OpenProcess( amask, 0, procid ) ;
  assert( hproc ) ;
  
  wchar_t* env = …
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> I was creating the derived class method definitions in a cpp file
> and couldn't get the project to progressively compile correctly.
> At my first method definition, a default constructor,
> the compiler kept spitting out this error message:

this is perhaps the most obscure error message that gcc (actually the linker) spits out, but the reason is simple:

the compiler has to put the (one and only one) vtable for a class into some object file or the other. it puts it into the object file for the translation unit where the definition of the first non-pure-virtual out-of-line virtual member function is present. if there is no such definition, you get this rather unhelpful linker error message.

you would be able to progressively compile the code even if a non-pure virtual function is not defined, but to be able to link without errors, every such function must have a definition (at least a stub). and to prevent the non-creation of a v-table by the compiler, at least one of the non-pure virtual functions will have to be defined out-of-line.

gcc has a faq about this: http://gcc.gnu.org/faq.html#vtables


> Am I to assume that the example in the book, as regards the inline feature
> of a derived class destructor, is in error.
i think it is not a particularly good book, but in this case neither the book nor the compiler is in error.

superjacent commented: To the point and relevant advice, thank you. +1
vijayan121 1,152 Posting Virtuoso

the missing argument appears to be the one to initialize the style member. based on comments in the base class, i guess that you are expected to pass "vintage" as the style for VintagePort .

vijayan121 1,152 Posting Virtuoso

> when i compile no errors but wen i build it i get 4 errors!
what are the errors? and which compiler are you using?

> if i want to hav the letter D il have to do the whole "*********\n", "** **\n", ..... thing is it??
yes, you need one pattern for each letter. and a look-up mechanism to get to the right pattern given a particular letter.

> im a super beginner!
perhaps you could attempt something simpler. eg. display a name like this:

***********************
 *                     *
 *  Aureliano Buendia  *
 *                     *
 ***********************
vijayan121 1,152 Posting Virtuoso

> how to display a letter with '*'s? for example, say the letter C
something like this, perhaps?

#include <iostream>

enum { HEIGHT = 8, WIDTH = 8 };

const char* const C_bitmap[HEIGHT] =
{
  "********\n", "********\n",
  "**\n", "**\n", "**\n", "**\n",
  "********\n", "********"
};

int main()
{
  for( int i=0 ; i<HEIGHT ; ++i )
    std::cout << C_bitmap[i] ;
  std::cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

> why do you have to 'state' the <<n1+n2 if it has already been 'stated' before in that line?
in your c++ program, you have to say precisely what is it that you want done. cout << n1 << " + " << n2 << " = " 'states' that you want the value of n1, a + sign, the value of n2 and an = sign to be sent to stdout.
you also need to 'state' that the value of n1+n2 and a newline are to be sent to stdout after the = sign.

vijayan121 1,152 Posting Virtuoso

hint:

char* punchmeinthehead( const char* first_name, 
                        const char* middle_name, 
                        const char* last_name )
{
   // ...
   // delete[] fullname ; // instead
   return fullname ;
}
vijayan121 1,152 Posting Virtuoso

were you looking for a standard library function?
like std::accumulate ( in header <numeric> )

// vec is a std::vector<int> and N <= vec.size()
int sum = std::accumulate( vec.begin(), vec.begin()+N, 0 ) ;
// average == sum / double(N)
VernonDozier commented: Useful function. +1
hammerhead commented: nice one +2
vijayan121 1,152 Posting Virtuoso

> Its true that a function would simplify a lot.
> I just have no idea how start it.
breaking it up into many small functions would simplify it even more. if the functions have meaningful names, the code would also be somewhat self-documenting.
this is one way of doing it (caveat: untested).

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <ctype.h>
using namespace std;

typedef string::size_type size_type ;

void fill_vector( const char* file_name, vector<string>& vec )
{
  ifstream file( file_name ) ;
  string str ;
  while( getline( file, str ) ) vec.push_back(str) ;
}

bool is_ws_delimited( const string& line, size_type pos,
                      size_type nchars )
{
  if( (pos!=0) && !isspace( line[pos-1] ) ) return false ;
  if( ( pos+nchars < line.size() ) &&
        !isspace( line[pos+nchars] ) ) return false ;
  return true ;
}

bool does_precede( const string& line, size_type pos,
                   const string& precede )
{
  size_type loc = line.rfind ( precede, pos );
  if( ( loc != string::npos ) &&
      is_ws_delimited(line,loc,precede.size()) )
  {
    loc += precede.size() ;
    if( loc >= pos ) return false ;
    for( size_type i = loc ; i<pos ; ++i )
    {
      if( !isspace( line[i] ) )
         return false ;
    }
    return true ;
  }
  return false ;
}

bool has_preceding_word( const string& line, size_type pos,
                         const vector<string>& prec_words )
{
  for( size_t i = 0 ; i < prec_words.size() ; ++i )
  {
    if( does_precede( line, pos, prec_words[i] ) )
       return true ;
  }
  return false ;
}

void …
vijayan121 1,152 Posting Virtuoso
std::ifstream fin( "file1.txt" ) ;
std::ofstream fout( "file2.txt" ) ;
fin >> std::noskipws ;
char ch ;
while( fin >> ch )
{
  if( ch == '[' ) fout << 'x' ;
  fout << ch ;
}
vijayan121 1,152 Posting Virtuoso

yup, the specific problem is here:

while((loc = /*vProperNouns[i]*/str.rfind(vPreceeding[j],
                                   pos)) != string::npos)

the more fundamental problem is the complexity of the code you have written. a while within a for within a while within a for!. why don't you simplify it by writing a function

bool does_precede( const string& str, const string& proper_noun, 
                                      const string& preceding_word ) ;

then you would have only loops nested one level (once in main and once in the function).

[It is] best to confuse only one issue at a time.

- K&R

vijayan121 1,152 Posting Virtuoso

> I'm planning on keeping everything in one source file
the file would be a header of this kind.

#ifndef _MY_LIBRARY_H_INCLUDED_ // include guard
#define _MY_LIBRARY_H_INCLUDED_ // include guard

#include <sstream>
#include <string>
#include <cstdlib>

namespace my_library
{
   // inline => internal linkage
   inline int digit( int number, std::size_t pos ) ;

   // const => internal linkage
   const int TEN = 10 ;

   // anonymous namespace => internal linkage
   namespace
   {
      int thousand = 1000 ;
      int sum_digits( int number ) ;
   }

   // static (deprecated) => internal linkage
   static int hundred = 100 ;
   static int product_digits( int number ) ;
}

//////////////////////////////////////////////////////
//                implementation
// may be in another file (say my_library.inc)
// which is #included here
// #include my_library.inc
//////////////////////////////////////////////////////

namespace my_library
{
   int digit( int number, std::size_t pos )
   {
     std::ostringstream stm ;
     stm << std::abs(number) ;
     const std::string& str = stm.str() ;
     if( pos < str.size() )
       return str[ str.size()-pos - 1 ] - '0' ;
     return -1 ;
   }

   namespace
   {
      int sum_digits( int number )
      {
        int sum = 0 ;
        int d = digit( number, 0 ) ;
        for( int i=0 ; d != -1 ; d = digit(number,++i) )
          sum += d ;
        return sum ;
      }
   }

   int product_digits( int number )
   {
        int prod = 1 ;
        int d = digit( number, 0 ) ;
        for( int i=0 ; d != -1 ; d = digit(number,++i) )
        {
          prod *= d ;
          if( prod == 0 ) …
vijayan121 1,152 Posting Virtuoso

you could also use the algorithm std::unique_copy .

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

struct consecutive_blanks
{
  bool operator() ( char first, char next ) const
  { return first==' ' && next==' ' ; }
};

int main()
{
  std::ifstream fin( "text_1.txt" ) ;
  fin >> std::noskipws ;
  std::ofstream fout("text_out.txt") ;
  std::istream_iterator<char> begin(fin), end ;
  std::ostream_iterator<char> dest(fout) ;
  std::unique_copy( begin, end, dest, consecutive_blanks() ) ;
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

ok. here is what you need to do.
download the following files:
http://www.agentpp.com/snmp++v3.2.23.tar.gz
http://www.agentpp.com/libdes-l-4.01a.tar.gz
http://www.agentpp.com/msvc7.zip
extract all three into the same directory (say C:\snmp_files)
your diectory structure now should be

snmp_files
         |
-------------------
|         |       |    
libdes   msvc    snmp++

open C:\snmp_files\msvc\static\snmp++\snmp++.vcproj in visual c++ ide
the project will need conversion (if you are using vc++ 2005 0r 2008),
let the ide convert it.

either add C:\snmp_files\libdes to your include path or
in C:\snmp_files\snmp++\src\auth_priv.cpp modify line 59
from #include <des.h> to #include "..\libdes\des.h" rebuild all.

the static library snmp++.lib would be created in
C:\snmp_files\msvc\static\debug (debug build)
C:\snmp_files\msvc\static\release (release build).

build other libraries in a similar fashion.

lAmoebal commented: Very Helpful +1
vijayan121 1,152 Posting Virtuoso

i think you would need to build the library from sources. (i can't test anything on windows; i'm on unix right now, and don't have a windows machine near me.). see what this is http://www.agentpp.com/msvc7.zip

vijayan121 1,152 Posting Virtuoso

i think you should look for a library with a name like libsnmp++.lib on unix, the libraries built are libsnmp++.a (static) and libsnmp++.so (shared). the one you have included is probably required too ( DES is an encryption standard).

i should have looked at the download page earlier. it does mention MS VC++7.0 Project Files http://www.agentpp.com/msvc7.zip perhaps you need to build the library from source. what does the README say?

vijayan121 1,152 Posting Virtuoso

the easiest fix would be to add the snmp++ library to your project. (the .lib file).

vijayan121 1,152 Posting Virtuoso

> Do you need makefiles for a windows platform?
you need some kind of a makefile. if you are using Visual C++, the project / workspace files also act as makefiles. you could set the preprocessor defines (WIN32 etc) in the project properties from the IDE. if you do not know how to do this, just add a #define WIN32 as the first line of the file you are trying to compile. before #include <snmp_pp_ext.h> > And as far as needing the Platform SDK headers in my include path, I set up the under Tools->Options->VC++ Directories->Include Files the directories linking to the include files in Visual Studio. Is this what you mean?
yes, that should be fine then. but this

#ifdef _MSC_VER
    typedef SOCKET SnmpSocket;
#else
    typedef int SnmpSocket;
#endif

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int suggests that it is not there in your include path. perhaps also add a #define _WIN32_WINNT 0x0501 ?

vijayan121 1,152 Posting Virtuoso

are you having -D__unix -I <include dirs> etc in your Makefile. if not, you could perhaps copy the preprocessor defines and compiler switches from the Makefile which came with the tarball.

instead of -D__unix, you would probably require a -DWIN32 on windows. do you have it? and for lines like this one typedef SOCKET SnmpSocket; , you would probably need the platform SDK headers in your include path.

vijayan121 1,152 Posting Virtuoso

it does build on FreeBSD. and therefore should build on Solaris.
here is an extract of the make output.
as you can see from it, the Makefile does not have anything special.
are you using the wrong Makefile? or a different version of the library?

root@/usr/ports/net-mgmt/snmp++:#make
=> snmp++v3.2.22.tar.gz doesn't seem to exist in /usr/ports/distfiles/.
=> Attempting to fetch from http://www.agentpp.com/.
snmp++v3.2.22.tar.gz                          100% of  255 kB   76 kBps
===>  Extracting for snmp++-3.2.22_2
=> MD5 Checksum OK for snmp++v3.2.22.tar.gz.
=> SHA256 Checksum OK for snmp++v3.2.22.tar.gz.
/bin/cp /usr/ports/net-mgmt/snmp++/files/Makefile.FreeBSD /usr/ports/net-mgmt/snmp++/work/snmp++/src
===>  Patching for snmp++-3.2.22_2
===>  Applying FreeBSD patches for snmp++-3.2.22_2
===>   snmp++-3.2.22_2 depends on executable: gmake - found
===>  Configuring for snmp++-3.2.22_2
===>  Building for snmp++-3.2.22_2
g++ -D_XPG4_EXTENDED -D__unix -Wall -D_USE_OPENSSL -I../include -I./ -I../../libdes -I../../crypt/src/headers -g  -o address.o -c address.cpp
g++ -D_XPG4_EXTENDED -D__unix -Wall -D_USE_OPENSSL -I../include -I./ -I../../libdes -I../../crypt/src/headers -g  -o asn1.o -c asn1.cpp
// .. etc
vijayan121 1,152 Posting Virtuoso

it is impossible to say just by looking at the fragments you posted. this one seems interesting.
> since this following code runs flawlessly while moving the snake around, there must not be a dangling pointer.

else if (next) // Runs only if it is has a proceeding  and succeeding segment, meaning 3 or more
    {
        lastx = x;
        lasty = y;
        x = previous->lastx;
        y = previous->lasty;
        dir = previous->dir;
        next->move();
    }

are you absolutely certain that this will never be called after SnakeSeg::kill has been called? you would be able to move the snake around flawlessly (kill has not been called); but by the time you reach the destructor things might have got out of hand.

in any case, do yourself a favour:
except in the destructor where you are deleting a member, never write delete ptr ; without also writing ptr = 0 ; immediately after that.
better still: completely avoid using c-style pointers whenever possible . prefer things like std::vector<>, std::auto_ptr<>, std::string, std::tr1::shared_pointer<> etc.

Joatmon commented: Solved my problem, thanks for the help +1
vijayan121 1,152 Posting Virtuoso
void SnakeSeg::erase()
{
    field[x][y] = 0; //field is a static member.
    putxy(x, y, ' '); // this code actually works to erase the snake when it is dead (when it goes into the deconstructor)
}

can cause such an error if and only if values of x and/or y are out of range.
print out the values of x, y in your destructor (or assert their validity) and you would discover that they are invalid. check the place where you had updated x, y for the last time before calling the destructor. and if the field array was dynamically allocated, that it has not been deleted before this.
i would be surprised if you did not have a dangling pointer. it would be a good idea to assert that x and y are in range every time you update them.