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

> CanvasObj class is defined as a template. Could that be a problem?
yes, it is a problem. but it is solved easily enough.
template typedefs are not legal in c++98. (they would be in c++0x)
as of now, you can not write

template< typename T > class CanvasObj ;

template< typename T >
typedef void ( CanvasObj<T>::*putptr_t )( int, int, unsigned long )  ;

the usual work around for this is to declare typedef inside a template class.

template< typename T > class CanvasObj ;

template< typename T > struct types
{
  typedef void ( CanvasObj<T>::*putptr_t )( int, int, unsigned long )  ;
  static putptr_t fputpix ;
};

template< typename T > typename types<T>::putptr_t types<T>::fputpix ;

template< typename T >
void setpix( typename types<T>::putptr_t fptr1 )
{
  types<T>::fputpix = fptr1;
}

/*
  called by CanvasObj class member as
    setpix( &(this->putpixel) )
*/

> My main motive is reusability here. So I don't want to change the C function.
the really serious problem is the one that bugmenot pointed out.
if the CanvasObj<T> object is a singleton, the problem is easily solved.
if not, it would require some complex (and ugly) code. it would be much easier and also much better to abandon the attempt at reusability of the C code. and rewrite the part involving the callback from scratch.

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
std::ifstream fin( "file1.txt" ) ;
std::ofstream fout( "file2.txt" ) ;
fout << fin.rdbuf() ;
vijayan121 1,152 Posting Virtuoso

something like this

// ...
loc = str.rfind ( str2, pos );
if (loc != string::npos)
{
  // check that there is at least one char between the words
  // ie. ( loc + str2.size() ) is less than  pos
  for( string::size_type i = loc + str2.size() ; i<pos ; ++i )
  {
    // check that every char in between is a space 
    // ie. str[i] is a space for every i
  }
  // ...
}
// ...
vijayan121 1,152 Posting Virtuoso
if( !word.empty() ) 
{
   if( word does not exist in tree )
   {
           Node node(word, page);
           avl.insert(node);
    }
    else 
   {
       Node* node = get the existing node for this word from avl
      node->incPages(page) ;
   }
    word = "";
}

this part of the code is truly horrible

if(c >=97 && c <= 122) {
            c = c-32;
   }
 if(c >= 65 && c <= 90) {
            word.append(1,c);
  }

use std::islower , std::toupper , std::isupper instead.

vijayan121 1,152 Posting Virtuoso

> Im using rfind() to search backwards but for some reason it starts the search
> from the beginning of the line and not from "pos" as i liked to rfind does start the search from pos as you expect.
but it returns the position where the matching subsequence begins
if you require the position of the last element of the subsequence, you can get it by

// rfind (like find) accepts a string
  loc = str.rfind ( str2 /*.c_str()*/, pos);
  if (loc != string::npos)
  {
    loc += str2.size() - 1 ;
    cout << "Match found ending at position: " << loc << endl;
  }
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

instead of this,

#include<string>
using namespace std;
#include<iostream.h> // no such header

write

#include<string>
#include<iostream> // the correct header
using namespace std; // moved down

also,

template <class TYPE, class KTYPE>
bool List<TYPE, KTYPE> :: _search (NODE<TYPE> **pPre, NODE<TYPE> **pLoc,KTYPE key,KTYPE key1)
{
  // Statements
  *pPre = NULL;
  *pLoc = head;
  if (count == 0)
  return false;

  // Test for argument > last node in list
  if (key > rear->data.key1)
  {
    *pPre = rear;
    *pLoc = NULL;
    return false;
  } // if

  while (key > (*pLoc)->data.key1)
  {
    // Have not found search argument location
    *pPre = *pLoc;
    *pLoc = (*pLoc)->link;
  } // while

  if (key == (*pLoc)->data.key1)// argument found--success
  {
    if(key1== (*pLoc)->data.key2)
    return true;
    // else 
       // what do you want to return? true or false?
  }
  else
    return false;
  // **** error: control reaches end of non-void function.
} // _search
vijayan121 1,152 Posting Virtuoso

> Do I just need to delete the individual parts of the array seperately?
the array geometryArray itself does not have a dynamic storage duration. (it was not allocated using new[] ).
therefore, delete [] geometryArray; is an error.
the contents of the array are pointers to objects allocated with a dynamic storage duration ( new ). you need delete on these pointers.

for( int i=0 ; i<GEOMETRY_COUNT ; ++i ) delete geometryArray[i] ;

note: Geometry requires a virtual destructor.

vijayan121 1,152 Posting Virtuoso

since the documents are html pages, you would need to remove the html formatting tags and all white space characters. (ie. just get the plain text of the document). this is required so that differences in fonts/character sizes/colours as well as differences in encoding of newlines etc. do not influence your check. now compute the MD5 checksum and the SHA256 checksum for it. if two documents have identical checksums for both SHA256 and MD5, conclude that they are the same document.

vijayan121 1,152 Posting Virtuoso

> I am using unique to get the unique elements from the row.
> But i am not getting the unique elements
the std::unique algorithm checks each two consecutive elements for equivalence; if you have two equivalent elements that are not next to each other, the second one will not be removed. std::unique does not work as you expect on a non-sorted range.

vijayan121 1,152 Posting Virtuoso

> My sources (MSDN) for map::erase(iterator) says that erase(iterator) returns an iterator ...

this is the interface given by dinkumware (and microsoft) for map<>::erase.

iterator erase(iterator where);
iterator erase(iterator first, iterator last);
size_type erase(const Key& keyval);

and this is the interface as per gcc (libstdc++)

void erase(iterator where);
void erase(iterator first, iterator last);
size_type erase(const Key& keyval);

for the first two functions, the dinkumware/microsoft signatures do not conform to c++98;
the gnu versions are the ones conforming to the standard.

however, the dinkum/microsoft signature for the first erase overload

iterator erase(iterator where);

would become the conforming one for c++0x.
see: http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/lwg-active.html#130

you can ignore the whole issue regarding the return type by writing the function this way

bool TCPIPRedirectManager::poll(){
   bool haveMsg = false;
   
   for(map<ConnHandle, TCPIPRedirect*>::iterator it = openPorts.begin(); it != openPorts.end(); ){
      if(it->second->poll()){
         haveMsg = true;
         }
      else if(it->second->shouldClose()){
         delete it->second;            // close the port   
         //it = openPorts.erase(it);          // <-- ##THIS IS THE PROBLEM LINE##
         openPorts.erase( it++ ) ; // conforming
         continue;                     // go to top - don't inc iterator
         }
      
      it++;
      }
      
   return haveMsg;
   }
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> In java I can use "object" class, because "object" class is father class of all class.
C programmers use void* where java programmers use object . you cannot use either without a cast; a wrong cast will result in unpleasant consequences in both. in C, incorrect runtime behaviour (seg fault etc.), in java an exception being thrown.
if object is the father, void* is the grandfather.

the solution in C++ depends on the paradigm that you want to use:
generic programming (typesafe):

template< typename T > class XX
{
   // ...
   private: T yy ;
   public:
      void setYY( const T& y ) { yy = y ; }
      const T& getYY() const { return yy ; }
      T& getYY() { return yy ; }
   // ...
};

object oriented programming (not so typesafe):
have a base class (say object) which all objects which can be put into an XX must inherit from.

struct  /* __declspec(novtable) */ object
{
   virtual ~object() = 0 { /* empty */ }
};
class XX
{
   // ...
   private: object* yy ;
   public:
      void setYY( object* y ) { yy = y ; }
      const object*getYY() const { return yy ; }
      object* getYY() { return yy ; }
   // ...
};

to use the object that is retrieved, a cast is required. in C++, this would be a dynamic_cast which may fail at runtime. this would mimic java fairly closely.

vijayan121 1,152 Posting Virtuoso

> I want the size of the vector to be 5x0.

for( size_t i = 0 ; i < event.size() ; ++i )
    event[i].clear() ;
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

The Windows platform sdk includes the Speech API (SAPI). it also comes with documentation.
http://www.microsoft.com/downloads/details.aspx?FamilyId=0BAF2B35-C656-4969-ACE8-E4C0C0716ADB&displaylang=en

vijayan121 1,152 Posting Virtuoso

> For better performance of the program (in terms of memory utilization
> and time for running the program) it is better to use vectors ...
a vector is just about the most efficient resizeable sequence container.

> Which data structure is best for fast search operation too?
if the keys on which you want to search are not volatile (ie. you fill the vector once and then they do not change), just use a std::binary_search after sorting the vector on keys (use std::sort for this)
if the keys do change, use an associative container like std::map

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
vijayan121 1,152 Posting Virtuoso

if you want to do some spirited programming ( http://www.boost.org/libs/spirit/index.html )

#include <boost/spirit/core.hpp>
#include <boost/spirit/actor.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using namespace boost::spirit;

bool parse_line( const char* cstr, vector<string>& words )
{
  subrule<0> top ;
  subrule<1> word ;

  return
     parse( cstr,

            //  begin grammar
            (
              top = str_p("Words:")
                           >> word >> *( ',' >> word )
                           >> ';' ,

              word = (+alpha_p)[ push_back_a( words ) ]
                           >> '(' >> digit_p >> ')'
            )
            ,
            //  end grammar

            space_p ).full ;
}

int main()
{
  string str[] =
  {
    "Words: One(1), Two(2);",
    " not words",
    "Words: boost(1), and(2), spirit(3), rule(4) ;",
    "Words: parse(1) fails(2), no(3), comma(4) ; ",
    "Words: parse(1), fails(x), wrong(3), digit(4) ; ",
    "Words: this(1), line(6), should(2), be(3), quite(4), ok(5) ;",
    "Words: parse(1), fai+ls(2), not(3), alpha(4) ; ",
  } ;
  for( size_t i=0 ; i < sizeof(str)/sizeof(*str) ; ++i )
  {
    vector<string> words ;
    if( parse_line( str[i].c_str(), words ) )
    {
        cout << "line " << i << " : " ;
        for( size_t i=0 ; i<words.size() ; ++i )
           cout << words[i] << ' ' ;
        cout << '\n' ;
    }
  }
}
[B]> g++ -Wall -std=c++98 -pedantic -Werror -I /usr/local/include parse_it.cc && ./a.out[/B]
line 0 : One Two
line 2 : boost and spirit rule
line 5 : this line should be quite ok
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
std::vector<int> row;
std::vector<std::vector<int> > event(5,row);
// note: every row is empty at this point

for(lv = 0; lv < event.size() ; ++lv )
{
  for( int gno=0 ; gno < event[lv].size(); ++gno )
  {
     // doing something
     // event[lv][gno] 
  }
// ...
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
int main()
{
  // ...
  cout << "How many messages do you want to enter? ";
  cin >> size;
  array = new messages[size];

  for (int i = 0; i < size; i++)
  {
    cout << "Message " << i+1 << ": ";
    //cin >> text;
    getline( cin >> ws, text ) ;
    array[i].message = text;

    cout << "Enter current time in Hours, Minutes & Seconds : " ;
    cin >> ws >> hrs >> mins >> secs;
    array[i].hours = hrs;
    // ...
   }
   // ...
}
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.

vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso
void SnakeSeg::kill()
{
    if (alive)
    {
        alive = false;
        erase();
        links = 0;
        if (next)
        {
            delete next; 
            next = 0 ; // isn't this required?
        }
    }
}
vijayan121 1,152 Posting Virtuoso

> So u mean there r no way to show the extended code(167)?

i mean that there is no *portable* way to show the extended code(167).
or any specific numeric code value (like 65) for that matter.

there are non-portable ways. for example, you could use the SetConsoleOutputCP function on windows. http://msdn2.microsoft.com/en-us/library/ms686036(VS.85).aspx

vijayan121 1,152 Posting Virtuoso

you could also use basic_string<>::find_first_not_of and basic_string::find_last_not_of to locate the characters at either end that are illegal in an email address. and the use basic_string<>::substr to extract the email address.

vijayan121 1,152 Posting Virtuoso

when you write a program, you express C source files as text lines containing characters from the source character set. when a program executes in the target environment, it uses characters from the target character set. these character sets are related, but need not have the same encoding.

this is all that you can assume:
every character set must contain a distinct code value for each distinct character in the basic C character set. the code value zero is reserved for the null character (and is always in the character set). code values for the digits are contiguous, with increasing values for characters from '0' to '9'. code values for any two letters (eg. 'a' and 'b') are not necessarily contiguous. code values for the basic C character set are positive when stored in an object of type char.

you can change locales and, therefore, target character sets while the program is running (by calling the function setlocale). the translator encodes character constants and string literals for the default "C" locale ( 'classic' locale in C++ ) which is the locale in effect at program startup.

> if i initialize x=65. it can show A
this is not guaranteed in any way. 65 may not be a code value in the target character set at all, or it may be the code value for some other character. you just happen to be running in a target environment where code value 65 maps to an 'A'.

vijayan121 1,152 Posting Virtuoso

or you could use the non-viral libcurl. http://curl.haxx.se/libcurl/

#include <curl/curl.h>
#include <iostream>
#include <algorithm>
#include <iterator>

struct stats
{
  stats() : bytes_recd(0), ncalls(0) {}
  int bytes_recd ;
  int ncalls ;
};

size_t on_data( void* buffer, size_t size, size_t nmemb, 
                void* pv )
{
 size_t nbytes = size * nmemb ;
 const char* chars = static_cast<const char*>(buffer) ;

 std::copy( chars, chars+nbytes,
        std::ostream_iterator<char>(std::cout) ) ;

 static_cast<stats*>( pv )->bytes_recd += nbytes ;
 ++ static_cast<stats*>( pv )->ncalls ;

 return nbytes ;
}

int main()
{
  stats statistics ;

  CURL* handle = curl_easy_init() ;
  curl_easy_setopt( handle, CURLOPT_URL, 
                    "http://curl.haxx.se/libcurl/") ;
  curl_easy_setopt( handle, CURLOPT_WRITEFUNCTION, on_data ) ;
  curl_easy_setopt( handle, CURLOPT_WRITEDATA, &statistics ) ;

  curl_easy_perform( handle ) ;

  std::cout << "\n--------------------------------------\n"
       << "received " << statistics.bytes_recd << " bytes in "
       << statistics.ncalls << " callbacks\n" ;
}

you need to link with libcurl:

>[B] g++ -Wall -std=c++98 -pedantic -Werror -I /usr/local/include -L /usr/local/lib -lcurl use_curl.cc && ./a.out[/B]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD> <TITLE>libcurl - the multiprotocol file transfer library</TITLE>
<meta content="text/html; charset=ISO-8859-1" http-equiv="Content-Type">
// ...
// elided
// ...
<!-- last-line-in-body -->
</BODY>
</HTML>
--------------------------------------
received 10857 bytes in 21 callbacks
vijayan121 1,152 Posting Virtuoso

> My thought was to make a .h file with a namespace. Would that work?
yes, provided that all the functions in the header have internal linkage. ie. they are inline or put in an anonymous namespace (or have the deprecated static linkage specifier). and you have an include guard for your header file.

> Or would I have to make a .dll?
if you have a header and seperate implementation files (.c .cc .cpp), you would need to make a library of some kind. either a static library or a shared library (dll).

> If so, how would I go about doing that?
depends on the toolset (microsoft/gnu/borland etc) that you are using.

vijayan121 1,152 Posting Virtuoso

> How do I pass a file or filename to a constructor?
write a constructor that takes a file name as the argument.

> And how do I retrieve "word_list" if I can't return from a constructor?
let the constructor store the words in a member variable. and provide an accessor function to retrieve the member.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

struct A
{
  explicit A( const std::string& file_name ) ;
  const std::vector< std::string >& word_list() const ;
  // ...

  private: std::vector< std::string > _word_list ;
  // ...
};

A::A( const std::string& file_name )
{
  std::ifstream file( file_name.c_str() ) ;
  std::string word ;
  while( file >> word ) _word_list.push_back(word) ;
}

const std::vector< std::string >& A::word_list() const
{ return _word_list ; }

int main()
{
  A object( __FILE__ ) ;
  const std::vector< std::string >& wl = object.word_list() ;
  // use wl
}
vijayan121 1,152 Posting Virtuoso

> ... develop a program that hides program files that should be kept out of sight in order to prevent them deleting any important files.
what right do you have to try to prevent users from deleting files on *their* computers?
to protect users from accidental deletion or overwrite, set the read only attribute.
http://msdn2.microsoft.com/en-us/library/aa365522(VS.85).aspx

vijayan121 1,152 Posting Virtuoso

you could use boost::progress_display http://www.boost.org/libs/timer/timer.htm

#include <boost/progress.hpp>
#include <iostream>
#include <unistd.h>

int main()
{
  enum { LINES_IN_FILE = 1000 } ;
  boost::progress_display display( LINES_IN_FILE, std::cout ) ;
  for( int i=0 ; i<LINES_IN_FILE ; ++i )
  {
    // process one line, add to database
    usleep( 10 ) ; // simulate taking 10 microsecs for this
    ++display ;
  }
}
vijayan121 1,152 Posting Virtuoso

> printing out the values to make sure they are correct they now look like this ...
the initial default precision for a stream is 6. to print out more decimal digits, do something like

std::cout << std::fixed << std::setprecision(8) 
          // 8 digits *after* decimal point
          << value ;

> I need absolute precision.
you will not get absolute precision with floating point values.
if the precision of a long double is not sufficient, you would either use integral types (numerator,denominator) or use a high precision arithmetic library.

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

// identifier messages causes a name clash with the facet
// because of the using directive (using namespace std)
struct message_t
{
    string message;
    int hours;
    int minutes;
    int seconds;
};

int main()
{
  int size;
  message_t* array;
  cout << "How many numbers?";
  cin >> size;
  array = new message_t;

  for (int i = 0; i < size; i++)
  {
    // ...
        string message ;
    int hours, minutes, seconds ;
    // no whitespaces allowed in the message string
    cin >> message >> hours >> minutes >> seconds ;
    array[i].message = message ;
    array[i].hours = hours ;
    // etc
  }
// ...
}
vijayan121 1,152 Posting Virtuoso

Curently allocated(4044MB)! if you are on a 32-bit machine, the address space is almost exhausted; you certinly won't get another 400 MB+ memory.

are you allocating this memory just once in your program?
if not are you freeing yhe allocated memory (VirtualFree with MEM_RELEASE) after use?

vijayan121 1,152 Posting Virtuoso

all literals (including literal strings) are immutable. they are const.
and therefore cannot be sorted (or modified in any way)

//char* a = "acbacb"; // bad programming practice
const char* a = "acbacb"; // the correct way
char b[] = "acbacb"; // also ok. a literal can be used to initialize
                    // an array of modifiable chars
vijayan121 1,152 Posting Virtuoso

> why is the value of RAND_MAX so much larger than mine ???
microsoft has always used a 16-bit value for computing rand(). as the generarator is a linear congruential one, this makes computation very fast. (multiplication can be done in a 32-bit register and the new value extracted by bit manipulation on the result). gcc uses 32-bit random numbers. perhaps, the microsoft implementation would change (with 64-bit processors becomming more common).

> But I think for the purposes of the OPs problem almost isn't good enough.
agreed. but only one random sample (from a normal distribution) needs to be generated.

#include <iostream>
#include <boost/random.hpp>
#include <cstdlib>

int main()
{
  boost::mt19937 rng ;
  boost::normal_distribution<> distr( RAND_MAX ) ;
  boost::variate_generator<boost::mt19937&,
        boost::normal_distribution<> > generator( rng, distr ) ;
  std::cout << std::fixed << generator() << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

'result' in the original problem is the sum of two random numbers.
and we are talking about the average value of a large number of samples, not any particular value.

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
  std::cout << "RAND_MAX: " << RAND_MAX << '\n' ;
  std::srand( std::time(0) ) ;
  for( int i=0 ; i<10 ; ++i )
  {
    enum { N = 1000000 } ;
    double sum = 0.0 ;
    for( int i=0 ; i<N ; ++i )
      sum += std::rand() + double( std::rand() ) ;
    std::cout << std::fixed << sum/N << '\n' ;
  }
}
RAND_MAX: 2147483647
2146112696.355224
2148536425.521353
2147638775.226065
2145940738.317371
2149102448.850054
2148997404.831785
2148572188.735253
2147364959.489652
2146814381.954062
2147781874.107042
vijayan121 1,152 Posting Virtuoso

> Basically, 2 numbers are randomly generated, and are added together
> to put in the variable 'result'. ...What I want to do is store every value and
> take an average at the end, to get an average of the results it gives me.

using rand() , each pseudo random number generated is in the range 0 to RAND_MAX. result would vary (non-uniformly) between 0 and RAND_MAX*2 with a mean of RAND_MAX. by the central limit theorem, we can replace this averaging by taking a single sample from the normal distribution. http://en.wikipedia.org/wiki/Central_limit_theorem (almost always it would be very very close to the mean RAND_MAX. the variace of the average would be only one millionth of the variance of the original distribution.)

vijayan121 1,152 Posting Virtuoso

not really. try 1.0, 2.0, 3.0, 4.0, 10.0
what is required is the number with the ordinal rank of 3.

using if as the *only* (control) statement? here's how you could do it for three integer numbers.

#include <iostream>
#include <algorithm>

int main()
{
   int lowest, /*low,*/ middle, /*high,*/ highest ;
   std::cin >> lowest >> middle ;
   if( middle < lowest ) std::swap( middle, lowest ) ;
   std::cin >> highest ;
   if( highest < middle )
   {
     std::swap( middle, highest ) ;
     if( middle < lowest ) std::swap( middle, lowest ) ;
   }
   std::cout << middle << '\n' ;
}