vijayan121 1,152 Posting Virtuoso

Visual Studio 2012 (November update).

Way ahead of GCC (the other major contender) in C++11 conformance - Microsoft has implemented almost everything in the standard.

clang 3.2 with its libc++ is on par with VS 2012; and it is somewhat more mature and stable in comparison. But it has to be built from sources; and installing it is not an easy task for everyone.

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

i would reconmend not using Xcode if your working on c++ becuse it uses the std c++ libray

There is nothing fundamentally wrong with Xcode as an IDE for C++.
You can't program in C++ - Xcode or no Xcode - without using the standard C++ library.

If Xmod had posted the code here (instead of linking to it), perhaps someone would have given an answer.

vijayan121 1,152 Posting Virtuoso

I'm using XCode on Mac OSX

If it's a recent version of GCC or clang, you should be able to compile the code with
-std=c++11 compiler option.

Otherwise:

std::string create_bit_sequence( const std::string& str )
{
    std::string result ;

    for( std::string::size_type i = 0 ; i < str.size() ; ++i  )
    {
        switch( str[i] )
        {
            case 'A' : result += "00" ; break ;
            case 'C' : result += "01" ; break ;
            case 'G' : result += "10" ; break ;
            case 'T' : result += "10" ; break ;
            default : { /* unexpected */ }
        }
    }

    return result ;
}
vijayan121 1,152 Posting Virtuoso

In general,
1. try to represent an elusive concept as a class - objects are more flexible than code.
2. C++ is one of the few programming languages with a strong sense of initialization and deinitialization - exploit it.

For example:

#include <iostream>

int recurse( int n )
{
    static int rdepth = 0 ;
    enum { TABSZ = 4 } ;

    struct trace_helper
    {
        explicit trace_helper( int n, const char* descr = "" )
            : arg(n), description(descr), tab( ++rdepth * TABSZ, ' ' )
        {
            std::cout << tab << "enter trace(" << arg << ") : "
                      << description << " \n" ;
        }

        ~trace_helper()
        {
            std::cout << tab << "exit trace(" << arg << ") : "
                      << description << " \n" ;
            --rdepth ;
        }

        const int arg ;
        const char* const description ;
        const std::string tab ;
    };

    trace_helper tracer( n, n <= 3 ? "n<=3 => return n*2 " :
                                     "n>3 => return recurse(n-3) + recurse(n-1)" ) ;

    return n <= 3 ? n * 2 : recurse(n-3) + recurse(n-1) ;
}
vijayan121 1,152 Posting Virtuoso

I want to give the customer a 'CurrentAccount' which is inherited from Account; and then store it in an array of Accounts.
How do I go about doing this?

You can't. Account acnts[10]; holds objects of type Account by value.
When you try to store an object of type CurrentAccount into that array it gets sliced.
http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c

Use an array of pointers to Account instead: Account* ptr_accts[10];

Note: Ideally std::shared_ptr<Account> or std::reference_wrapper<Account> depending on the storage duration; but this may be beyond what you have learned till now.

vijayan121 1,152 Posting Virtuoso

Simplest: use std::ifstream for input, std::ofstream for output.

// read from file
{
    std::ifstream file( FILENAME ) ; // open file for input

    // read stuff
    // ...

} // file is closed when the stream goes out of scope

// over-write the contents of the file
{
    std::ofstream file( FILENAME ) ; // open file for output (truncated)

    // write stuff
    // ...

} // file is closed when the stream goes out of scope

If you want to use the same (ope)n std::fstream for both reading and writing, after reading, before over-writing:
a. clear any possible error state
b. seek to the beginning of the stream

vijayan121 1,152 Posting Virtuoso

Read 20 chars into a std::string:

#include <fstream>
#include <string>

int main()
{
    std::ifstream file( "file.txt" ) ;
    std::string str ;
    enum { NCHARS = 20 } ;

    // read upto NCHARS chars into str
    str.reserve(NCHARS) ; // not essential
    file >> std::noskipws ; // do not skip white space on formatted char input
    char c ;
    while( ( file >> c ) && ( str.size() < NCHARS ) ) str += c ;

    // use str
}
vijayan121 1,152 Posting Virtuoso

srand(time(NULL));

Not a good idea to reseed the linear congruential rng each time the function is called.
Perhaps something like: static int seed_once = ( std::srand( std::time(0) ), 0 ) ; instead.

Or better still, just document that std::rand() is used; and expect main() to call std::srand().

C++11:

#include <string>
#include <random>
#include <ctime>

std::string random_str( std::size_t len )
{
    static const std::string a = 
              "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ;
    static std::mt19937 rng( std::time(0) ) ;
    static std::uniform_int_distribution<std::size_t> distr( 0, a.size() - 1 ) ;

    std::string r ;
    for( std::size_t i = 0 ; i < len; ++i ) r += a[ distr(rng) ] ;
    return r ;
}
vijayan121 1,152 Posting Virtuoso

reverting to building both with /MDd made the program work

Building both with /MD would also work; other combinations would fail.

You don't want to return a vector like that because it has to be duplicated when returned, which can be very very time consuming

I do. Returning the vector by value is just as efficient and leads to cleaner code.
http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

vijayan121 1,152 Posting Virtuoso

deleted

vijayan121 1,152 Posting Virtuoso

A one-off calculation of the hamming distance between two strings would take O(N) time. This code would not be noticeably faster - but it is perhaps cleaner.

#include <string>

std::size_t hamming_distance( const std::string& a, const std::string& b )
{
    if( a.size() != b.size() ) return -1 ;
    std::size_t hd = 0 ;
    for( std::size_t i = 0 ; i < a.size() ; ++i ) hd += ( a[i] == b[i] ) ;
    return hd ;
}

#include <fstream>

int main()
{
    std::ifstream file( "file" ) ;
    std::string a, b ;
    std::getline( file, a ) ;
    while( std::getline( file, b ) )
    {
        std::size_t distance = hamming_distance( a, b ) ;
        // use distance
    }
}

If you are repeatedly calculating the hamming distance with a constant set of strings in the file, optimizations may be possible. For instance, encode the genome strings into a bit sequence and then calculate using bit-wise operations (with a std::bitset<>)

#include <unordered_map>

std::string create_bit_sequence( const std::string& str )
{
    static std::unordered_map<char,std::string> m =
                   { { 'A', "00" }, { 'C', "01" }, { 'T', "10" }, { 'G', "11" } } ;
    std::string result ;
    for( char c : str ) result += m[c] ;
    return result ;
}
vijayan121 1,152 Posting Virtuoso

I'm not sure what you mean

While building the DLL and the exe, for both use the same shared (DLL) version of the C/C++ runtime library.
http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx

vijayan121 1,152 Posting Virtuoso

You need to link both the DLL and the exe to the same instance of the run-time library.

Ie. link both with the shared version of the standard library: either /MDd (Debug) or /MD (Release)

vijayan121 1,152 Posting Virtuoso

Ideally use a std::vector<> to hold the names and numbers.

If you must use arrays (you have a teacher ... ), you need to keep track of the size manually. Something like:

struct PhoneBook
{
    // ...
    void add( const Name& n, const PhoneNumber& p )
    {
        if( current_size < MAXSZ )
        {
            aNames[current_size] = n ;
            aNumbers[current_size] = p ;
        }
        else { /* error: no more space */ }
    }

    const PhoneNumber& find( const Name& n ) const
    {
        // look into the names array and get the position,
        // return number at that position
        for( std::size_t pos = 0 ; pos < current_size ; ++pos )
           if( aNames[pos] == n ) return aNumbers[pos] ;

        // error: not found - return something invalid (or throw)
        static const PhoneNumber no_phone_number = "-1" ;
        return no_phone_number ;
    }

    private:

        static constexpr std::size_t MAXSZ = 1000 ;
        Name aNames[ MAXSZ ] ;
        PhoneNumber aNumbers[ MAXSZ ] ;
        std::size_t current_size = 0 ;
};
vijayan121 1,152 Posting Virtuoso

why the remove and rename function cannot perform?
everytime remove the original (hello.txt), it still remain.

Probaly because you have not closed the files before attempting these operations.

#include <cstdio>
#include <fstream>
#include <string>
#include <iostream>

std::string replace( std::string line, const std::string& substr,
                                       const std::string& replace_with )
{
    std::string::size_type pos = 0 ;
    while( ( pos = line.find( substr, pos ) ) != std::string::npos )
    {
        line.replace( pos, substr.size(), replace_with ) ;
        pos += replace_with.size() ;
    }
    return line ;
}

int main()
{
    const char* const original_file_name = "whatever" ;
    std::string original_substr, replacement ;
    std::cin >> original_substr >> replacement ;

    // get a temporary file name
    char tmp_file_name[ L_tmpnam ] ;
    std::tmpnam(tmp_file_name) ;

    // create a temporary file with replaced text
    {
        std::ifstream original_file(original_file_name) ;
        std::ofstream temp_file(tmp_file_name) ;
        std::string line ;
        while( std::getline( original_file, line ) )
            temp_file << replace( line, original_substr, replacement ) << '\n' ;
    }

    // overwrite the original file with the temporary file
    {
        std::ifstream temp_file(tmp_file_name) ;
        std::ofstream original_file(original_file_name) ;
        original_file << temp_file.rdbuf() ;
    }

    // and delete the temporary file
    std::remove(tmp_file_name) ;
}
vijayan121 1,152 Posting Virtuoso

You are trying to access elements beyond the end of the vector (in at least two places).

And you probably need to take care of of narrowing conversions: int f = pow(2,log10(k));

vijayan121 1,152 Posting Virtuoso

IS? What is that?

IS (in a C++ context) is an abbreviation for the International Standard for C++ (ISO/IEC 14882).

If it's allowed why is the warning still being issued?

The IS permits a compiler to emit a warning or informational diagnostic for any construct in a program. All that is required for conformance is that a correctly formed program must be accepted and compiled.

Such diagnostics (which are not errors) are extremely useful - they draw the attention of the programmer to a possible unintentional logical error. For example:

struct S
{
    S( int i ) : b(i), a(b-1) // *** warning: 'S::b' will be initialized after 'S::a'
                              // [ is this intentional? ]
    {
        if( i = 0 ) // warning: assignment used as truth value
                    // [ did you intent to write if( i == 0 )? ]

        {
            // ...
        }
    }

    int a ;
    long b ;
};
vijayan121 1,152 Posting Virtuoso
//double getMean( double scores[], int numScores )
double getMean( const double scores[], int numScores ) // **** const
{ 
    /*
    // You may want to ignore this bit for now.
    using limits = std::numeric_limits<double> ;
    if( numScores < 1 )  
        return limits::has_quiet_NaN ? limits::quiet_NaN() : limits::signaling_NaN() ;
    */

    // int Sum = 0; 
    double Sum = 0.0 ; // **** Sum is of type double

    // ...
vijayan121 1,152 Posting Virtuoso

Something like this:

// C++11
std::string generate_file_name( const std::string& name, const std::string& college )
{
    static int slno = 0 ;
    return name + '_' + college + '_' + std::to_string( ++slno ) ;
}


// or C++98
std::string generate_file_name( const std::string& name, const std::string& college )
{
    static int slno = 0 ;
    std::ostringstream stm ;
    stm << name << '_' << college << '_' << ++slno ;
    return stm.str() ;
}
vijayan121 1,152 Posting Virtuoso

Write it in two stages, perhaps.

You already have the code for converting a decimal number to some specified base.
Write the code to convert in the reverse direction - from some specified base to decimal.

Now conversion from base A to base B can be done in stages:

  • Convert number in base A to decimal.
  • Convert the decimal result to base B.
vijayan121 1,152 Posting Virtuoso

but it seems to suggest the opposite of what vijayan121 said.

Yes, brace elision is allowed by the IS.

An array is an aggregate that can be initialized with the syntax
array<T, N> a = { initializer-list };
where initializer-list is a comma-separated list of up to N elements whose types are convertible to T.

Mea culpa; there is a mistake in what I had posted. Both g++ (4.8) and clang++ (3.1) just give a warning, not an error. Corrected below:

struct X { int a[2] ; } ;
X one = { 1, 2 } ; // ***warning: missing braces around initializer for 'int [2]'
X two = { { 1, 2 } } ; // fine
vijayan121 1,152 Posting Virtuoso

std::array<> is an aggregate which wraps a C-style array. It has no user-defined constructors.
{1,2,3,4,5}is therefore not interpreted as a brace-enclosed initializer_list<>

The situation is analogous to:

struct X { int a[2] ; } ;
X one = { 1, 2 } ; // ***error: missing braces around initializer for 'int [2]'
X two = { { 1, 2 } } ; // fine
vijayan121 1,152 Posting Virtuoso

std::ifstream file("d:\hebro4.w3c") ;// * ** * error in path to file

std::ifstream file( R"(d:\hebro4.w3c)" ) ; // raw literal string
or std::ifstream file( "d:\\hebro4.w3c" ) ; // escape sequence
or std::ifstream file( "d:/hebro4.w3c" ) ; // posix path

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

where can i put thes code?

Anywhere. For instance, you could call the function split_into_ws_separated_columns() from main()

int main()
{
    std::ifstream file( "d:\\h1.txt" ) ;
    std::string line ;
    while( std::getline( file, line ) )
    {
       std::cout << "line: " << line << '\n' ;
       std::vector< std::string > cols = split_into_ws_separated_columns(line) ;
       for( std::size_t i = 0 ; i < cols.size() ; ++i )
        std::cout << "\tcolumn #" << i << ": " << cols[i] << '\n' ;
    }
}
vijayan121 1,152 Posting Virtuoso

How to print a sentence (including white spaces) from a file ?
Or How to print entire text file which has a paragraph?

Assunming that you have a compiler that is not antique:

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

int main()
{
    std::string filename ;
    std::cout << "file mame? " && std::cin >> filename ;
    std::ifstream file( filename.c_str() ) ;
    std::cout << file.rdbuf() ;
}
Daniel BE commented: I'm using Turbo C 4.5 +0
vijayan121 1,152 Posting Virtuoso

Split the line using a std::istringstream ?

#include <vector>
#include <string>
#include <sstream>

std::vector< std::string > split_into_ws_separated_columns( 
                                      const std::string& line_from_file )
{
    std::vector< std::string > columns ;
    std::istringstream stm(line_from_file) ;
    std::string col ;
    while( stm >> col ) columns.push_back(col) ;
    return columns ;
}
L7Sqr commented: Much cleaner approach. +8
vijayan121 1,152 Posting Virtuoso

Still making a wild guess as to what is it that you really want.

Assuming that you want to print out the contents of a standard sequence container along with a tag indicating the type of the container and its value_type
(via a function which is not an overloaded operator):

#include <typeinfo>
#include <string>

template< typename T > std::string type_name() ;

#ifdef __GNUG__

#include <cxxabi.h>

template< typename T > std::string type_name()
{
    char temp[ 2048 ] ;
    std::size_t sz = sizeof(temp) ;
    int status ;
    __cxxabiv1::__cxa_demangle( typeid(T).name(), temp, &sz, &status ) ;
    return temp ;
}

#else // not GNU compatible

template< typename T > std::string type_name() { return typeid(T).name() ; }

#endif // __GNUG__

#include <iostream>
#include <vector>
#include <list>

template < typename SEQUENCE_CONTAINER >
std::ostream& print( const SEQUENCE_CONTAINER& seq, std::ostream& stm = std::cout )
{
    const std::string cntr_name = type_name<SEQUENCE_CONTAINER>() ;
    const std::string value_type_name = type_name< 
                                     typename SEQUENCE_CONTAINER::value_type >() ;
    stm << cntr_name.substr( 0, cntr_name.find('<') ) << " of " 
        << value_type_name << " [ " ;
    for( const auto& v : seq ) stm << v << ' ' ;
    return stm << ']' ;
}


int main()
{
    std::vector< std::string > a = { "how", "now", "brown", "cow" } ;
    print(a) << '\n' ; // prints: std::vector of std::string [ how now brown cow ]

    std::list<double> b = { 1.2, 3.45, 6.789 } ;
    print(b) << '\n' ; // prints: std::list of double [ 1.2 3.45 6.789 ]
}
vijayan121 1,152 Posting Virtuoso

Something like this:

#include <iostream>
#include <vector>

template < typename T > struct my_class : public std::vector<int>
{
    typedef std::vector<T> base ;
    using base::iterator ;
    // etc

    explicit my_class( const char* n ) : name(n) {}

    // ...

    private: std::string name ;

    friend inline std::ostream& operator<< ( std::ostream& stm, const my_class<T>& mc )
    {
        stm << mc.name << ": [ ";
        for( const T& v : mc ) stm << v << ' ' ;
        return stm << ']' ;
    }
};

int main()
{
    my_class<int>  VecOfInts( "A vector of integers" ) ;
    VecOfInts.push_back(3) ;
    VecOfInts.push_back(2) ;
    VecOfInts.push_back(1) ;
    std::cout << VecOfInts << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

Now I just have to alter it so it doesn't read in repeat words in the book.

The simplest way would be to use a std::set<> or std::unordered_set<> to filter out the non-uniqe words.

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

// http://en.cppreference.com/w/cpp/container/vector
std::vector< std::string > unique_words( const char* path2file )
{
    std::ifstream file( path2file ) ;

    // http://en.cppreference.com/w/cpp/iterator/istream_iterator
    std::istream_iterator< std::string > begin(file), end ;

    // http://en.cppreference.com/w/cpp/container/set
    std::set< std::string > unique( begin, end ) ;

    return std::vector< std::string >( unique.begin(), unique.end() ) ;
}

Note: This snippet is merely illustrative; it does not take care of punctuation in the text.

vijayan121 1,152 Posting Virtuoso
void encode()
{
    char userInput[512], direction[32], keyword[32];
    int transposition;

    cout << "Enter the text to be encoded: ";
    cin.get( userInput, sizeof(userInput) ) ; // unformatted input

    cout << "Enter direction (Forwards or Reverse): ";
    cin.get( direction, sizeof(direction) ) ; // unformatted input

    cout << "Enter transposition value (0...25): ";
    cin >> transposition; // formatted input
    cin.ignore( 1000, '\n' ) ;

    cout << "Enter a keyword for Vigenere encryption: ";
    cin.get( keyword, sizeof(keyword) ) ; // unformatted input
}

See: http://www.cplusplus.com/forum/general/69685/#msg372532

vijayan121 1,152 Posting Virtuoso

Let us say we have a function:

// return a string with all occurrences of substr in str replaced with replacement  
std::string replace_all( const std::string& str, const std::string& substr, 
                         const std::string& replacement ) ;

This function can be called with many different input sets (each set being a tuple of three strings). A specific invocation of the function with a given input set is an instance. To analyuse its time and space complexity, we need to consider what happens as the size of data increases - what are the characteristics of the input data set which will affect performance? An instance characteristic is a (typically numeric) measure of the proiperties of the input data that has a bearing on performance.

In the above example, the instance characteristics would be
N - the length of str
K - the length of substr
L - the length of replacement

We would aim to estimate performance of the function as time(N,K,L) or space(N,K,L)

vijayan121 1,152 Posting Virtuoso

The singleton design pattern is unique in that it's a strange combination: its description is simple, yet its implementation issues are complicated. - Andrei Alexandrescu in 'Modern C++ Design'

If Animal is a singleton - that is a second object of type Animal cannot exist - its singletonness can be enforced by the class Animal and by the class Animal alone.

This is one typical way of ensuring that one - and only one - instance of an object of dynamic type 'some unknown derived class of Animal' can exist at any point of time.

    //////////////  animal.h ///////////////////

    struct Animal
    {
        static Animal& get_it() ;

        virtual ~Animal() ;
        virtual int age() const = 0 ;
        virtual void speak() = 0 ;

        Animal( const Animal& ) = delete ; // non-copyable
        Animal( Animal&& ) = delete ; // and non-movable

        protected: Animal() ;
    };

--------------------------------

//////////////  animal.cc ///////////////////

#include "amnimal.h"
#include <atomic>
#include <mutex>
#include <stdexcept>

namespace
{
    std::atomic<Animal*> singleton(nullptr) ;
    std::mutex guard ;
}

Animal::Animal() // a constructor of a derived class will invoke this constructor
{
    if(singleton) throw std::logic_error( "Animal is a singleton" ) ;
    else singleton = this ;
}

Animal::~Animal() { singleton = nullptr ; }

Animal& Animal::get_it()
{
    std::lock_guard<std::mutex> lock(guard) ;

    if( !singleton ) throw std::logic_error( "singleton instance not created" ) ;
    else return *singleton ;
}

------------------------------

///////////////// main.cc ///////////

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

int main()
{
    struct Zebra : Animal
    {
        virtual int age() const override …
vijayan121 1,152 Posting Virtuoso

Toggle a boolean flag, perhaps?

const int arr[3][3] = { 
                        { 23, 54, 76 },
                        { 37, 19, 28 },
                        { 62, 13, 19 },
                      } ;

bool alt = true ;
for( const auto& row : arr ) for( int i : row )
{
  if(alt) std::cout << i << '\n' ;
  alt = !alt ;
}
vijayan121 1,152 Posting Virtuoso

I can only use either putback or peek methods...

std::istream::peek() provides look-ahead for just one character, not more. So what you are trying to do is not possible (portably). You need to use atleast one function that will extract the character just peeked so that you can now peek at the next character in the input buffer - for instance, std::istream::ignore(1) will extract and throw away one character from the input buffer.

I need to read the first charachter

Reading the first character from the input buffer is easy - throw away leading white-space characters, peek to retrieve the first non-whitespace char, and then remove that char from the input buffer.

than I need to read two number, ignore everything in between

Reading in a number is a bit more interesting.
a. Throw away characters one by one till the next character is a digit.
b. Retrieve the first digit character.
c. Remove it from the input buffer.
d. Repeat for each digit in the input immediately following the first digit - read its value, update the value of the number, and remove that character from the input buffer.

#include <iostream>
#include <cctype>

char extract_char()
{
    // throw away leading white space
    while( std::isspace( std::cin.peek() ) ) std::cin.ignore(1) ;

    // retrieve the first non-whitespace char
    int c = std::cin.peek() ;
    std::cin.ignore(1) ; // and remove it from the input buffer

    return char(c) ;
}

inline int extract_first_digit()
{
    // …
vijayan121 1,152 Posting Virtuoso

Use std::map<> with
std::pair< e_ServerName1, e_ServerName2 > as the key_type
and e_UserName as the mapped_type.
http://en.cppreference.com/w/cpp/container/map

#include <map>

enum e_UserName { one, two, three, four /* etc. */ } ;

enum e_ServerName1 { Venus, Mars, Earth } ;

enum e_ServerName2 { Jupiter, Pluto, Neptune, Saturn } ;

int main()
{
    std::map< std::pair< e_ServerName1, e_ServerName2 >, e_UserName > look_up ;
    look_up[ std::make_pair(Venus,Pluto) ] = three ;
    look_up[ std::make_pair(Earth,Jupiter) ] = one ;
    // etc

    e_ServerName1 a = Earth ;
    e_ServerName2 b = Jupiter ;
    auto iter = look_up.find( std::make_pair(a,b) ) ;
    if( iter != look_up.end() ) // found it
    {
        e_UserName user_name = iter->second ;
        // do whatever with user_name
    }
}
vijayan121 1,152 Posting Virtuoso

I can't figure out how to use the cin.peek for the extracting numbers or charachters from the randomly typed input

std::istream::peek() will retrieve, but will not extract the character from the input buffer (the charaxter remains in the input buffer).
http://en.cppreference.com/w/cpp/io/basic_istream/peek

Use std::istream::get() to read and extract the next character.
http://en.cppreference.com/w/cpp/io/basic_istream/get

#include <iostream>

int main()
{
    // retrieve the next character without extracting it
    using traits_type = std::istream::traits_type ;
    traits_type::int_type c = std::cin.peek() ;
    if( c != traits_type::eof() )
         std::cout << "peeked char is: " << traits_type::to_char_type(c) << '\n' ;

    // read (and extract) the next character
    char ch ;
    if( std::cin.get(ch) ) std::cout << "extracted char is: " << ch << '\n' ;
}
vijayan121 1,152 Posting Virtuoso
vijayan121 1,152 Posting Virtuoso

MSYS is a collection of GNU utilities such as bash, make, gawk and grep to allow building of applications and programs which depend on traditionally UNIX tools to be present. http://www.mingw.org/wiki/MSYS

Once we have MSYS, building open source libraries for MinGW is not very different from building open source libraries on Unix.

Here is a brief tutorial to get you started:
http://www.ibm.com/developerworks/linux/tutorials/l-compiling/

You might also want to have a glance at:
gnu make: http://www.gnu.org/software/make/manual/make.html
gnu automake: http://www.gnu.org/software/automake/manual/html_node/index.html
gnu configure: http://airs.com/ian/configure/
gnu autoconf: http://www.gnu.org/savannah-checkouts/gnu/autoconf/manual/autoconf-2.69/html_node/index.html

Overview of linking with external libraries:
http://www.linuxtopia.org/online_books/an_introduction_to_gcc/gccintro_17.html

GCC link option -l http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html#Link-Options
GCC directory options -L -I http://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html#Directory-Options

vijayan121 1,152 Posting Virtuoso

(4/(2*n-1) results in integer division.
Instead, you need something like 4.0 / ( 2*n - 1 )

To get alternative plus and minus signs, we do not need the expensive and approximate std::pow().

Something like this:

// pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... )

int sign = +1 ;
double pi = 0.0 ;
constexpr int n = 1000000 ;

for( int i = 0 ; i < n ; ++i )
{
    pi += sign * 4.0 / ( i*2 + 1 ) ;
    sign = -sign ;
}

std::cout << std::fixed << pi << '\n' ;
vijayan121 1,152 Posting Virtuoso

To read a whole line (including whitespace) into a string, use std::getline()
http://www.cplusplus.com/reference/string/getline/

To read the contents of a file, where each data set consists of the name of a state followed by three numbers, the code would be something like:

std::ifstream file ("list.txt") ;
std::string name_of_state ;
int number ;
int month ;
int year ;

// check success or failure *after* (and not before) the attempted input.
// this is idiomatic - while we have read some data successfully ...  
while( std::getline( file, name_of_state ) && file >> month >> year )
{
    // discard everything up to and including the next newline
    file.ignore( 1024, '\n' ) ; // *** see note below

    // validate month, year etc.

    // use the data that has been read.
}

Note: to understand why std::istream::ignore() is needed, see:
http://www.cplusplus.com/forum/general/69685/#msg372532

vijayan121 1,152 Posting Virtuoso

The Nuwen build of MinGW includes a number of pre-built libraries; libjpeg-8d is one of them. http://nuwen.net/mingw.html

Nuwen MinGW is distributed as a single self-extracting archive and can be installed from the command line.

vijayan121 1,152 Posting Virtuoso

I am facing problem using float
in loop its value stuck at 8388608.00

First read up a bit on the representation of floating point numbers and loss of precision.
http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html

Then, try out this program:

#include <limits>
#include <iostream>
#include <iomanip>

int main()
{
    typedef std::numeric_limits<float> limits ;
    std::cout << "exponent ranges from: " << limits::min_exponent << " to "
              << limits::max_exponent << " binary ie. about "
              << limits::min_exponent10 << " to " << limits::max_exponent10
              << " decimal\nmantissa has " << limits::digits << " binary digits "
              << "ie. about " << limits::digits10 << " decimal digits\n" ;

    const unsigned long long max_mantissa = ( 1U <<  (limits::digits-1) ) - 1 ;
    std::cout << std::fixed << std::setprecision(limits::digits10)
              << "max value of normalised mantissa: " << max_mantissa << '\n' ;

    float big = max_mantissa ;
    float small = 0.1 ;

    float a = big, b = small, c = -a ;
    std::cout << "a == " << a << '\n' ;
    std::cout << "b == " << b << '\n' ;

    std::cout << "a+b == " << a+b << '\n' ;
    std::cout << "a-b == " << a-b << '\n' ;
    std::cout << "a+b+c == " << a+b+c << '\n' ;
    std::cout << "a+c+b == " << a+c+b << '\n' ;
}

Can you explain the output?

This is the output on my implementation:

exponent ranges from: -125 to 128 binary ie. about -37 to 38 decimal
mantissa has 24 …

vijayan121 1,152 Posting Virtuoso

+1 Gonbe and deceptikon.

People do learn by going through, reasoning about, and then understanding a solution to a problem. Someone learning programming is not all that much different from a child learning to speak - the child learns by listening to people speak correctly.

vijayan121 1,152 Posting Virtuoso

Something like this:

enum { N = 1024*1024*1024 } ; // 1G times
double value = 1.0 / 3.0 ;

double plus_result = 0 ;
for( int i=0 ; i < N ; ++i ) plus_result += value ;

const double multiplies_result = value * N ;

std::cout << std::fixed << std::setprecision( std::numeric_limits< double >::digits10 )
          << "plus_result: " << plus_result << '\n'
          << "multiplies_result: " << multiplies_result << '\n' ;
vijayan121 1,152 Posting Virtuoso

void DeleteRepeats(char array[], int size, int sizeUnique) is not const-correct.
A const-correct version would be:
void DeleteRepeats( const char array[], int size, int sizeUnique )
http://www.cprogramming.com/tutorial/const_correctness.html

http://www.parashift.com/c++-faq-lite/overview-const.html

Also, void DeleteRepeats(char array[], int size, int sizeUnique ) does not return anything to the caller. It is just a function for printing out the unique (non-duplicated) characters in the input array.

For that, you just need to iterate through each char in the input array and then print it out if it is not present at an earlier position in the array. And perhaps the function could have been given a more meaningful name. Something like this would suffice, wouldn't it?

// is char at array[pos] a duplicate? (present at an earlier position in the array)
bool is_duplicate( const char array[], std::size_t pos )
{
    for( std::size_t i = 0 ; i < pos ; ++i )
       if( array[i] == array[pos] ) return true ;

    return false ;
}

// print out each unique char in the array
void print_unique( const char array[], std::size_t size )
{
    for( std::size_t i = 0 ; i < size ; ++i ) // for each position i in the array
        if( !is_duplicate( array, i ) ) // if the char at array[i] is not a duplicate
            std::cout << array[i] ; // print it out
    std::cout << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

std::size_t defined in the header <cstddef> can store the maximum size of a theoretically possible object of any type (including array).

std::size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.

from: http://en.cppreference.com/w/cpp/types/size_t

vijayan121 1,152 Posting Virtuoso

Is such a thing possible?

Yes. You would find it easier to solve a bigger problem by breaking it down into a set of smaller problems, each of which is easy to solve. For example:

Problem : return a dynamically allocated array containing unique chars from the input array.

Sub-problem one: check if a char in the array is a duplicate char. Is it present at an earlier position in the array?

// is char at array[pos] a duplicate? (present at an earlier position in the array)
bool is_duplicate( const char array[], std::size_t pos )
{
    for( std::size_t i = 0 ; i < pos ; ++i )
       if( array[i] == array[pos] ) return true ;

    return false ;
}

Sub-problem two: How many unique characters are there in the input array?

// get a count of unique chars in the array
std::size_t count_unique( const char array[], std::size_t size )
{
    std::size_t unique_cnt = 0 ;

    for( std::size_t i = 0 ; i < size ; ++i )
        if( !is_duplicate( array, i ) )  ++unique_cnt ;

    return unique_cnt ;
}

The bigger problem can now be reduced to:
a. Determine the number of unique characters are there in the input array
b. Dynamically allocate an array of that many chars.
c. For each char in the input array, if it is not a duplicate, copy it to the result array

char* array_without_dups( const char array[], std::size_t size, 
                          std::size_t& no_dups_array_size ) …
vijayan121 1,152 Posting Virtuoso

As of now, in terms of strict conformance, clang with its libc++ is ahead of the rest of the pack.
http://clang.llvm.org/

It is also the best compiler for people starting out to learn C++; clang's clear and expressive diagnostic messages are much easier for beginners to understand. (GCC 4.8 has narrowed the gap).