vijayan121 1,152 Posting Virtuoso

> is asio as robust as ACE?

Probably not. ACE has been in wide use for a much longer time.

> the performance between asio and ACE

ACE is heavyweight in terms of memory footprint; asio is not.

In terms of speed, it shouldn't make a difference: you can execute a few million instructions in the time it takes to send a single packet over TCP/IP.

> could I use asio and ACE together?

You certainly could. But ACE does tend to impose a particular architectural structure for your program, which it supports quite well; with asio you might have to write some extra code to conform to that architecture.

vijayan121 1,152 Posting Virtuoso

Copy the shared library (dll) to the directory where the program using it (exe) is present.

Or one of the directories listed here: http://msdn.microsoft.com/en-us/library/7d83bc18%28v=VS.100%29.aspx

vijayan121 1,152 Posting Virtuoso

> i thought that template <typename T> is for fundamental types and template <class T> is for user defined types.
> ... what is the main difference between them?

There is no difference.

vijayan121 1,152 Posting Virtuoso

> wouldn't it make sense to change them to by default be explicit?

Yes, it would. If it was meditated on right at the outset, I guess the keyword would have been implicit - constructors would have been explicit by default.

However, an important consideration during standardization is that when a new feature is introduced, existing valid, well-written code should continue to work the same way. So, the keyword added was explicit - the default bahaviour is implicit, as it had been earlier.

vijayan121 1,152 Posting Virtuoso

Your class should be something like this:

class phone
{
    public:
        // The type member is an enumeration of HOME, OFFICE, FAX, CELL, and PAGER
        enum phone_type_t = { HOME, OFFICE, FAX, CELL, PAGER } ; // *** added

        phone();
        //phone(int coCode, int arCode, int phNumber); // optional

        // A constructor that enables all of the values to be set should be provided as well.
        phone(int coCode, int arCode, int phNumber, phone_type_t phone_type ) ; // *** added

        // constructor that takes just the number and type as arguments, and sets the country and area codes to those of your location
        phone( int phNumber, phone_type_t phone_type ) ; // added

        int GetcoCode() const; //observer
        int GetarCode() const; //observer
        int GetphNumber() const; //observer
        // TODO: add observer for phone type

        // transformers that allow each data member to be changed
        void SetcoCode( int coCode ) ; // added
        // TODO: add other transformers.

        // Shouldn't comparison for equivalence should return a bool?
        /*Contact*/ bool /*ComparedTo*/ Equals( const phone& otherphone ) const ; // make const-correct

    private:
        int countryCode;
        int areaCode;
        int phoneNumber;

        phone_type_t type ; // *** added
};
vijayan121 1,152 Posting Virtuoso

> Can I add up the memory values of A through F and then add them up
> for whatever variant on them is passed and see if those two values are equal?

No. (why?)

One way is to use the == operator of std::set<>

std::string str = "vjjjJGJGJGJgjjVHhACDBFEfhyffhyfhyfhyf" ;
const std::set<char> abcdef = { 'A', 'B', 'C', 'D', 'E', 'F' } ;

for( auto iter = str.begin() ; iter < str.end() - abcdef.size() + 1 ; ++iter )
{
     if( std::set<char>( iter, iter+abcdef.size() ) == abcdef )
     {
         // found it
     }
}
vijayan121 1,152 Posting Virtuoso

> I need to know how to make it pull just the information that I need to compare.

For input, use std::ifstream

To read line by line from the stream, use std::getline

To extract the information from the line, use std::istringstream

For example,

std::ifstream old_file( "oldfile.dat" ) ;
    std::string line ;
    while( std::getline( old_file, line ) )
    {
        int ac_number ;
        std::string first_name ;
        std::string last_name ;
        double balance ;

        std::istringstream istm(line) ;
        if( istm >> ac_number >> first_name >> last_name >> balance )
        {
            // do something with the data
        }
    }

See: http://www.arachnoid.com/cpptutor/student2.html

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

> how are they referring to references being safe?

Who are 'they'?

I think they are trying to say:

void foo( A& a ) ; // we can assume that a refers to a valid object
// unless code that results in undefined behaviour has been executed 
// prior to the invocation of the function.  

void bar( A* pa ) ; // we cannot assume that pa points to a valid object
// even if code that results in undefined behaviour has never been executed 
// prior to the invocation of the function.

This would lead to undefined behaviour

int& function()
{
     int variable = 3;
     return variable&;
}

So would this:

int* pointer = new int(100) ;
int& reference = *pointer ;
delete pointer ;
reference = 7 ;

This too:

int i = 100 ;
int& r = i ;
double& reference = reinterpret_cast<double&>(r) ;
reference += 5 ;

As well as this:

int* pointer = nullptr ;
int& reference = *pointer ;
delete pointer ;
reference = 7 ;

And so forth.

vijayan121 1,152 Posting Virtuoso

A good starting point is Jack Crenshaw's "Let's Build a Compiler!"
http://www.penguin.cz/~radek/book/lets_build_a_compiler/

vijayan121 1,152 Posting Virtuoso

Template instantiation is done at compile-time; no there is no run-time overhead for instantiating a template.

> but I am not sure how implicit function invokation works.
> I don`t think compiler will create a different function for evey datatype available
> (since there can be many different data-types in one program).

Yes. AFAIK, every implementation creates a different instantiation each time. This can lead to code bloat for template functions containing a significant amount of code; you may want to write your code in such a way that this issue is addressed.
See: http://drdobbs.com/184403053

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.9
Some what dated; in current C++, you would use std::enable_if<> and friends.

C++ requires that each template instatiation occurs exactly once in the program if it is needed, and not at all otherwise. There is also a code bloat problem if the implementation violates this rule. I haven't checked the situation with the more recent versions, but g++ used to be (and probably still is) a notorious violator.
See: http://docs.freebsd.org/info/gcc/gcc.info.Template_Instantiation.html

vijayan121 1,152 Posting Virtuoso

> hours worked is 70, so the output should read 1 week, 3 days, 6 hours.
> this is assuming the work week is 40 hours with 8 hour days.

70 / 40 == 1 (integer division)
70 % 40 == 30 (modulus) http://www.vias.org/cppcourse/chap04_01.html
30 / 8 == 3
30 %8 == 6

vijayan121 1,152 Posting Virtuoso

> I am just wondering if this is necessary or if I can write the functions in normal c++ as well.

No, it isn't necessary. As always, you would need to build both the library and the program using the library with the same compiler (version).

> Oh, also what other types of syntax can be used in static libraries?

Anything that you could use in a program without libraries.

vijayan121 1,152 Posting Virtuoso

An external merge sort using four files, perhaps?

http://en.wikipedia.org/wiki/Merge_sort#Use_with_tape_drives

vijayan121 1,152 Posting Virtuoso

For each class, you need to have a header file x.h and an implementation file x.cpp.
Include the header file in order to use the class.

For example:

//////////// duties.h /////////////////

#ifndef DUTIES_H_INCLUDED_
#define DUTIES_H_INCLUDED_

#include <string>

class Duties
{
    public: static void submitChangeDutyRequests( const string& ) ;
};

#endif // DUTIES_H_INCLUDED_
//////////// duties.cpp //////////////////

#include "duties.h"

void Duties::submitChangeDutyRequests( const string& requests )
{
   // ...
}
////////// homepage.h /////////////////////

#ifndef HOMEPAGE_H_INCLUDED_
#define HOMEPAGE_H_INCLUDED_

#include <string>

class HomePage
{
    public: static void HsubmitChangeDutyRequests( const string& ) ;
};

#endif // HOMEPAGE_H_INCLUDED_
//////////// homepage.cpp //////////////////

#include "homepage.h"
#include "duties.h"

void HomePage::HsubmitChangeDutyRequests( const string& requests )
{
   Duties::submitChangeDutyRequests( requests ) ;
}
////////////  main.cpp ////////////////////////

#include <iostream>
#include "homepage.h"

int main()
{
    // ...
    std::string request ;
    while( std::cout << "request? " && std::getline( std::cin, request ) )
    {
        // ...
        HomePage::HsubmitChangeDutyRequests(request) ;
        // ...
    }
}
vijayan121 1,152 Posting Virtuoso

It's not an OS or IDE issue.

#include "Queue.h"
#include "Queue.cpp"

int main()
{
	Queue <int> q;	// q is an object

	q.showQ();
	q.insert(72);
   
        // ...
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

> At first, I wrote something like this

template<typename T, size_t size>
inline size_t const sizeof_array(T const [size]){return size;}

> but if failed...Why version one fail?


The reason is extremely simple:

1. These three are different ways of declaring the same function - one which takes a single parameter of type int*

void function( int a[100] ) ;
void function( int a[] ) ;
void function( int* a ) ;

2. Top level references are dropped during deduction. Try this:

#include <iostream>
#include <typeinfo>
#include <cxxabi.h> // GNU C++ specific
#include <string>

template< typename T > std::string type_name() // GNU C++ specific
{
    enum { MAX_LEN = 2048 } ;
    char name[MAX_LEN] = "" ;
    std::size_t sz = MAX_LEN ;
    int status ;
    __cxxabiv1::__cxa_demangle( typeid(T).name(), name, &sz, &status ) ;
    return status==0 ? name : "__cxa_demangle error" ;
}

template< typename T > void foo( T arg )
{
    std::cout << "foo - type T is: " << type_name<T>() << '\n' ;
}

template< typename T > void bar( T& arg )
{
    std::cout << "bar - type T is: " << type_name<T>() << '\n' ;
}

int main()
{
    int i = 100 ;
    int& ref = i ;
    foo(ref) ; // type T is: int (top-level reference is dropped)

    int a[100] = {0};
    int (&ref_array)[100] = a ;
    foo(ref_array) ; // type T is: int* (top-level reference is dropped)
    foo<int(&)[100]>(a) ; // type T is: int[100]
    bar(a) ; // type T …
vijayan121 1,152 Posting Virtuoso

> Does anyone has a brilliant (and simple!) way to selectively control access
> by giving different rights to different friends?

I don't have anything brilliant, but using access helpers to provide selective access is reasonably simple.

class A
{
    void foo() {}
    void bar() {}

    // grant void foo_not_bar( A& ) access to foo, but not to bar
    // grant void bar_not_foo( A& ) access to bar, but not to foo

    public :
        class foo_access_helper
        {
           private: static void foo( A& a ) { a.foo() ; }
           friend void foo_not_bar( A& ) ;
        };
        friend class foo_access_helper ;

        class bar_access_helper
        {
           private: static void bar( A& a ) { a.bar() ; }
           friend void bar_not_foo( A& ) ;
        };
        friend class bar_access_helper ;
};

void foo_not_bar( A& a ) { A::foo_access_helper::foo(a) ; }

void bar_not_foo( A& a ) { A::bar_access_helper::bar(a) ; }
vijayan121 1,152 Posting Virtuoso

The simplest solution is to use std::vector<>

std::vector< std::vector<int> > matriceVilles( 25, std::vector<int>(25) ) ;

void affichageMatrice( const std::vector< std::vector<int> >& m ) ;

and so on.

In most cases, there is no good reason to mess around with C-style arrays of arrays in a C++ program.

vijayan121 1,152 Posting Virtuoso

> Does this occur with such reliability that I should pass and return any arbitrary object by value?

Copy elision is allowed, but not mandated by IS. You can’t write portable code with the assurance that copy elision would be performed.

In practise, mainstream compilers do implement copy elision, at least for RVO and NRVO. However, many opportunities for for copy elision are missed by every compiler.

In general, this is what I follow:
a. Return moveable objects by value. (almost everything in the standard library is moveable.)
b. If the function does not need to modify (a copy of) the object, pass by reference to const.
c. If the function needs to make a mutable copy, pass by value. (If a copy must be made, leaving the details to the compiler would not be less efficient and may result in more optimal code. For example:

std::vector<int> sorted_sequence( std::vector<int> seq )
{
    std::sort( seq.begin(), seq.end() ) ;
    return seq ;
}
vijayan121 1,152 Posting Virtuoso

Oh yeah will this work in ofstream?

Yes. std::ofstream is a std::ostream.

C++11: Just use raw string literals.

std::cout << R"---(The path is "C:\Equation_MinGW\bin\g++.exe". (C++11))---" << '\n' ;

   std::cout << R"(menu
----
   1. one
   2. two
   3. three
   )" ;

See: http://www2.research.att.com/~bs/C++0xFAQ.html#raw-strings

vijayan121 1,152 Posting Virtuoso

Once you have fixed the constructor (test<int> => test<T>), fix the template friend declaration.

See: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16

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

> Normally you wouldn't use a function to create a vector anyway,
> since returning it (and thus causing it to be copied) is not efficient.

Not really.

Dave Abrahams in 'Want Speed? Pass by Value.' - http://cpp-next.com/archive/2009/08/want-speed-pass-by-value explains why:

Be honest: how does the following code make you feel?

std::vector<std::string> get_names();
…
std::vector<std::string> const names = get_names();

Frankly, even though I should know better, it makes me nervous. In principle, when get_names() returns, we have to copy a vector of strings. Then, we need to copy it again when we initialize names, and we need to destroy the first copy. If there are N strings in the vector, each copy could require as many as N+1 memory allocations and a whole slew of cache-unfriendly data accesses as the string contents are copied.

Rather than confront that sort of anxiety, I’ve often fallen back on pass-by-reference to avoid needless copies:

void get_names(std::vector<std::string>& out_param );
…
std::vector<std::string> names;
get_names( names );

Unfortunately, this approach is far from ideal.

  • The code grew by 150%
  • We’ve had to drop const-ness because we’re mutating names.
  • As functional programmers like to remind us, mutation makes code more complex to reason about by undermining referential transparency and equational reasoning.
  • We no longer have strict value semantics for names.

But is it really necessary to mess up our code in this way to gain efficiency? Fortunately, the answer turns out to be no (and especially …

vijayan121 1,152 Posting Virtuoso

> why they needed to make 2 types of strings, char string and w_char string?

A few years down the line, they realized that two types of strings are nowhere near enough; so now we have five.

std::string str = "hello world\n" ; // string where char_type is char
    std::wstring wstr = L"hello world\n" ; // string where char_type wchar_t
    std::string utf8str = u8"hello world\n" ; // utf-8 encoded UNICODE string
    std::u16string u16str = u"hello world\n" ; // utf-16 encoded UNICODE string
    std::u32string u32str = U"hello world\n" ; // utf-32 encoded UNICODE string

You might want to read this:
http://www.joelonsoftware.com/articles/Unicode.html

vijayan121 1,152 Posting Virtuoso

If we call rand5() seven times and add up the results, we would get an integer in the inclusive interval [7,35].
Divide this number by 5.0 and we would get a real number in the inclusive interval [1.0,7.0].

Take care of the round-off correctly (how?) and you have rand7().

vijayan121 1,152 Posting Virtuoso

> i am using windows 7 64 bit OS, Dev C++ compiler.
> which compiler should i use?

Dev C++ is the IDE; you are probably using an archaic version of the Mingw port of GNU compiler (g++ 3.4 or so).

This would be a more reasonable choice of IDE and compiler:
http://prdownload.berlios.de/codeblocks/codeblocks-10.05mingw-setup.exe

This is another:
http://sourceforge.net/projects/codelite/files/Releases/codelite-3.0/codelite-3.0.0.5041-mingw4.4.1.exe/download

Or this:
http://go.microsoft.com/?linkid=9709949

If you are using the GNU compiler (g++), set the options which would make g++ become a C++ compiler: --std=c++0x --pedantic-errors

preferably along with: -Wall -Wextra -Werror

vijayan121 1,152 Posting Virtuoso
int i=0,a[length],j=0; // *** error: ISO C++ forbids variable length array 'a'
vijayan121 1,152 Posting Virtuoso

Something like this:

const std::string SINGLE = "Single" ;
    const std::string MARRIED = "Married" ;
    const std::string INVALID = "??????" ;
    
    if( marital_status == 1 ) std::cout << SINGLE ;
    else if( marital_status == 2 ) std::cout << MARRIED ;
    else cout << INVALID ;

Alternatively, use a switch-case.

You need to: #include <string> and also perhaps validate user input.

vijayan121 1,152 Posting Virtuoso

> Little optimization if there are millions of keys and million of values per keys.

Neat! That's not just a 'little optimzation'; it's a lot more efficient and also more elegant than my feeble effort.

Bravo!

In fact, line 4 is not required; the loop takes care of an empty multi_map<> as well.
Reduces to just three lines:

template< typename K, typename T, typename C, typename A >
typename std::multimap<K,T,C,A>::size_type num_unique_keys( const std::multimap<K,T,C,A>& mmap )
{
    typename std::multimap<K,T,C,A>::size_type n = 0 ;
    for( auto iter = mmap.begin() ; iter != mmap.end() ; iter = mmap.upper_bound(iter->first) ) ++n ;
    return n ;
}
vijayan121 1,152 Posting Virtuoso

I would suggest that you study the fundamental concepts involved in concurrent programming. Understanding that is the harder and the important part.

Learning to use thread facilities provided by a particular platform or library is the easy part; it gives you the tools, but you need to know when and how to use those tools.

Here are two references to get you started:
http://www.amazon.com/Synchronization-Algorithms-Concurrent-Programming-Taubenfeld/dp/0131972596
http://www.amazon.com/Art-Multiprocessor-Programming-Maurice-Herlihy/dp/0123705916

vijayan121 1,152 Posting Virtuoso

Since std::multimap<> stores the keys in an ordered manner,

#include <map>

template< typename K, typename T, typename C, typename A >
typename std::multimap<K,T,C,A>::size_type num_unique_keys( const std::multimap<K,T,C,A>& mmap )
{
    if( mmap.size() < 2U ) return mmap.size() ;

    const C& cmp = mmap.key_comp() ;
    typename std::multimap<K,T,C,A>::size_type n = 1 ;
    auto prev = mmap.begin()->first ;

    for( auto iter = mmap.begin() ; iter != mmap.end() ; ++iter )
        if( cmp( prev, iter->first ) ) { ++n ; prev = iter->first ; }

    return n ;
}

Obviously, this won't work with std::unordered_multimap<>.

alwaysLearning0 commented: cool +5
vijayan121 1,152 Posting Virtuoso

> why it is not in the std::tuple or boost::tuples::tuple class since other operators are already defined (comparison).

IIRC, there was a suggestion to overload the + operator for std::tuple<>. Not for element by element arithmetic plus, but for concatenation of tuples a la std::string.

There would be a similar ambiguity in the case of operator- (element by element minus or symmetric difference?), operator* ( element by element multiply, vector cross product or scalar dot product?).

IMHO, it was best that none of these operators were overloaded by the standard.

vijayan121 1,152 Posting Virtuoso

> I can't see why "double-checked locking" would cause race condition?

See: http://drdobbs.com/cpp/184405726

This conclusion was true (for C++03) at the time the article was written.

Nothing you do can alter the fundamental problem: You need to be able to specify a constraint on instruction ordering, and your language gives you no way to do it.

The good news is that C++ now gives fine-grained control over memory ordering and sequencing.
See: http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-6-double-checked-locking.html

For your specific example, the simple solution is to place the initialization in a static variable at block scope.

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization ....

With footnote: The implementation must not introduce any deadlock around execution of the initializer. - FDIS

See: http://www.devx.com/SpecialReports/Article/38883/1954

Note: with the caveat

If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

vijayan121 1,152 Posting Virtuoso

Well, the DLL code will have complete access to the address space of the process.
Access to external resources (files etc) can be restricted by loading it into a sandbox.

Get an impersonation token with limited access rights/privileges
http://msdn.microsoft.com/en-us/library/aa378184.aspx

In a thread of your process, impersonate the user with limited access
http://msdn.microsoft.com/en-us/library/aa378612.aspx

Load the library, make all library function calls and unload the library from threads with impersonation turned on.

Caveat: I know nothing (absolutely nothing) about any Windows OS after XP; the above may or may not apply to Vista and the like.

vijayan121 1,152 Posting Virtuoso

It would be hard to beat the blitz::TinyVector for performance.

http://www.oonumerics.org/blitz/docs/blitz_7.html#SEC131

vijayan121 1,152 Posting Virtuoso

> there are 2 common ways to loop through a vector

Perhaps four.

#include <vector>
#include <algorithm>

void one( std::vector<int>& seq ) { for( auto& i : seq ) ++i ; }

void two( std::vector<int>& seq )
{ for( auto iter = seq.begin() ; iter != seq.end() ; ++iter ) ++*iter ; }

void three( std::vector<int>& seq )
{ for( std::vector<int>::size_type i = 0 ; i < seq.size() ; ++i ) ++seq[i] ; }

void four( std::vector<int>& seq )
{ std::for_each( seq.begin(), seq.end(), []( int& i ) { ++i ; } ) ; }

It is clearly a quality of implementation issue; but one could expect the generated code to be almost identical for all four.

Well not quite.

The GNU compiler generates identical code for one, two and four, but trips up on three (array subscript).

#include <vector>
#include <algorithm>

/**********************************************************************
>g++ --std=c++0x -Wall -Wextra -Werror --pedantic -c -S -O3 -fomit-frame-pointer
**********************************************************************/


void one( std::vector<int>& seq )
{ for( auto& i : seq ) ++i ; }
/*********************************************************************
    movl    4(%esp), %edx
    movl    (%edx), %eax
    movl    4(%edx), %edx
    cmpl    %edx, %eax
    je  L1
L3:
    addl    $1, (%eax)
    addl    $4, %eax
    cmpl    %eax, %edx
    jne L3
L1:
    rep
    ret
**********************************************************************/


void two( std::vector<int>& seq )
{ for( auto iter = seq.begin() ; iter != seq.end() ; ++iter ) ++*iter ; }
/*********************************************************************
    movl    4(%esp), %edx
    movl    (%edx), %eax
    movl    4(%edx), %edx
    cmpl    %edx, %eax
    je  L6
L8:
    addl    $1, (%eax)
    addl    $4, %eax
    cmpl    %eax, %edx …
vijayan121 1,152 Posting Virtuoso

> The thing is that we dont know that the address p is address of b

Then there is no way to reliably determine the address of the struct object.

vijayan121 1,152 Posting Virtuoso

Use a Threadpool Cleanup Group to manage graceful shutdown.

http://msdn.microsoft.com/En-US/library/ms682036%28v=VS.85%29.aspx

vijayan121 1,152 Posting Virtuoso

You don't need anything more than the offsetof macro in <cstdddef>

#include <cstddef>
#include <iostream>

struct A
{
    int a ;
    int b ;
    char c ;
    // ...
};

void foo( int* p ) // address of A::b
{
    A* pa = reinterpret_cast<A*>( reinterpret_cast<char*>(p) - offsetof(A,b) ) ;
    std::cout << "foo::pa: " << pa << '\n' ;
}

int main()
{
    A aa ;
    std::cout << "&main::aa: " << &aa << '\n' ;
    foo( &aa.b) ;
}
vijayan121 1,152 Posting Virtuoso

This is what TR 18015 : Technical Report on C++ Performance has to say about the costs of exception handling:

For some programs, difficulty in predicting the time needed to pass control from a throw-expression to an appropriate catch clause is a problem. This uncertainty comes from the need to destroy automatic objects and – in the “table” model – from the need to consult the table. In some systems, especially those with real-time requirements, it is important to be able to predict accurately how long operations will take. For this reason current exception handling implementations may be unsuitable for some applications. However, if the call tree can be statically determined, and the table method of EH implementation is used, it is possible to statically analyze the sequence of events necessary to transfer control from a given throw-expression to the corresponding catch clause. Each of the events could then be statically analyzed to determine their contribution to the cost, and the whole sequence of events aggregated into a single cost domain (worst-case and best-case, unbounded, indeterminate). Such analysis does not differ in principle from current time estimating methods used for non-exception code.

In short, rather than making blanket assumptions about the performance cost of throw/catch constructs, one needs to devote some time to analyzing the costs. The results would vary widely depending on both the program being analyzed and the implementation's exception-mechanism design trade-offs.

The entire report is freely available: http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf
Worth re-reading if C++ performance …

mike_2000_17 commented: Confirms what I thought! Very interesting report! +14
vijayan121 1,152 Posting Virtuoso
#include <sstream>
#include <exception>

class ConversionException: public std::exception
{
    virtual const char* what() const throw()
    {
        return "Bad Conversion";
    }
} convertError;

template<typename To, typename From>
const To Convert(const From & convertFrom)
{
    To convertTo;
    std::stringstream ss;
    ss << convertFrom;
    if(ss >> convertTo)
        return convertTo;
    throw convertError;
}

int main()
{
    double d = 1.0e+8 ;
    std::cout << int(d) << ' ' << Convert<int>(d) << '\n' ; 
    // prints 100000000 1
}

If there is a direct convertible, you should use that instead of performing the conversion via a stringstream. At best it could be inefficient; in many cases it can yield an incorrect result.

Some thing like this would be required:

#include <iostream>
#include <sstream>
#include <type_traits>
#include <stdexcept>

struct bad_conversion : public std::logic_error
{
    bad_conversion() : std::logic_error( "bad conversion" ) {}
};

template< typename TO, typename FROM > inline TO convert( const FROM& from,
    typename std::enable_if<std::is_convertible<FROM,TO>::value,void>::type* = nullptr )
{ return TO(from) ; }

template< typename TO, typename FROM > inline TO convert( const FROM& from,
    typename std::enable_if< !std::is_convertible<FROM,TO>::value, void >::type* = nullptr )
{
    TO to ;
    std::stringstream stm ;
    if( stm << from && stm >> to ) return to ;
    else throw bad_conversion() ;
}

int main()
{
    double d = 1.0e+8 ;
    std::cout << int(d) << ' ' << convert<int>(d) << '\n' ;
    // prints 100000000 100000000
}
vijayan121 1,152 Posting Virtuoso

char thousands[] = {"", "M", "MM", "MMM", "MMMM"}; This is an error; thousands is an array of chars, not an array of c-style strings.
You need to do something like this instead. const char* thousands[] = {"", "M", "MM", "MMM", "MMMM"}; > i have one error, which is C2110: cannot add two pointers.

If you want to use the + operator to concatenate strings, use std::string instead of c-style string.

char a[100] = "abcd" ;
const char b[] = "ef" ;
a = a + b ; // *** error *** 

std::string c = "abcd" ;
c = c + b ; // fine

See: http://www.cprogramming.com/tutorial/string.html

vijayan121 1,152 Posting Virtuoso

> I used getline to read the first line and to check for spaces

By default, formatted input ignores whitespaces. input >> nextChar ; // nextChar contains the next non-whitespace char So,

#include <fstream>
#include <cctype>

// good if there are digits at the beginning and end of file
bool good_file( const char* const path )
{
    std::ifstream file(path) ;

    // try to read the first non-ws char and check if it is a digit
    char first_non_ws ;
    if( file >> first_non_ws && std::isdigit(first_non_ws) )
    {
        char last_non_ws = first_non_ws ;
        while( file >> last_non_ws ) ; // read till the last non-ws char
        return std::isdigit(last_non_ws) ;
    }
    else return false ;
}
vijayan121 1,152 Posting Virtuoso

Your program is running out of memory.

See: http://www.cplusplus.com/reference/std/new/bad_alloc/

vijayan121 1,152 Posting Virtuoso

> I am trying to compile this example http://www.boost.org/doc/libs/1_42_0/...
> and I am getting the error "/usr/local/boost_1_47_0/...

There is a version mismatch. The code for 1.47.0 would be:

BOOST_FOREACH( const std::string& name, m_modules )
{
   // pt.put( "debug.modules.module", name, true ) ;
   pt.add( "debug.modules.module", name, true ) ;
}

See: http://www.boost.org/doc/libs/1_47_0/doc/html/boost_propertytree/tutorial.html

vijayan121 1,152 Posting Virtuoso

> Do I need to be careful?

If you decide to be careful, the code would be something like:

wchar_t wc = L'A' ;
    char c = 'A' ;
    const auto& ctype = std::use_facet< std::ctype<wchar_t> >( std::locale() ) ;
    if( ctype.widen(c) == wc ) { /* whatever */ }
vijayan121 1,152 Posting Virtuoso

> I'm having issues with processing the tokens that I've made.

Make the task easier by using std::string.

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::string line ;
    while( std::cout << '>' && std::getline( std::cin, line ) )
    {
        // tokenize the line on white space
        std::string token ;
        std::istringstream stm(line) ;
        while( stm >> token )
        {
            std::cout << "token: " << token << '\n' ;
            if( token == "this_token" )
            {
                // ...
            }
            else if( token == "some_other_token" )
            {
                // ...
            }
            // etc
        }
    }
}
vijayan121 1,152 Posting Virtuoso

Assuming that shell32.dll exports a function with that signature with the entry point at ordinal 262,

a. Load shell32.dll into the process address space.
b. Get the address of the function at ordinal 262
c. Call the function.

Something like:

#include <windows.h>

int main()
{
   CoInitialize(0) ;
   {
       const char* const DLLNAME = "shell32.dll" ;
       enum { ORDINAL = 262 } ;
       typedef void __stdcall function_type( const wchar_t*, int, const wchar_t* ) ;
       typedef function_type* function_pointer_type ;

       function_pointer_type function_pointer = function_pointer_type(
                                        GetProcAddressA( LoadLibrary(DLLNAME),
                                        reinterpret_cast<const char*>(ORDINAL) ) ) ;

       wchar_t user_name[] = L"put user name here" ;
       wchar_t path[] = L"put path to picture file here" ;

       function_pointer( user_name, 0, path ) ;
   }
   CoUninitialize() ;
}

(Error handling is elided).