vijayan121 1,152 Posting Virtuoso

> calculate the modulo-10 of the value using % ...
the value may be negetive; you need to adjust for that.

al alternative is
a. convert the number to a string
b. reverse the string
c. convert the string back to a number.
eg.

int reverse( int number )
{
  bool negetive = number < 0 ;
  if( negetive ) number = -number ;
  
  ostringstream ostm ;
  ostm << number ;
  string str = ostm.str() ;
  // c++0x => string str = lexical_cast<string>(number) ;
    
  reverse( str.begin(), str.end() ) ;

  istringstream istm(str) ;
  int result ;
  istm >> result ;
  // c++0x => int result = lexical_cast<int>(str) ;

  return negetive ? -result : +result ;
}
vijayan121 1,152 Posting Virtuoso

> if the only datatypes in Vehicle are int cylinders and string manufacturer, do I really need to check before assigning?
you really do not need to write an assignment operator at all; the compiler will synthesize a (non-trivial) assignment operator with the correct semantics.

> If so, what's the point?
only efficiency (avoid the call to string's operator=, which would check for a self assignment in any case).

vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <iomanip>
#include <fstream>
#include <limits>
#include <cmath>
using namespace std;

inline bool is_equal( double x, double y )
{
   const double epsilon = std::numeric_limits<double>::epsilon() ;
   return std::fabs( x-y ) <= epsilon * std::fabs(x) ;
   // see Knuth's The Art of Computer Programming
   // Volume 2 - Seminumerical Algorithms
   // section 4.2.2 pages 217-218
}

int main()
{
  double largest = -1.0 ;
  double second_largest = -1.0 ;
  int largest_count = 0 ;
  int second_largest_count = 0 ;

  ifstream infile("sales3.txt");
  int id ;
  double sales ;
  cout << fixed << setprecision(2) << showpoint ;
  
  while( infile >> id >> sales )
  {
    cout << id << ' ' << sales << '\n' ;
    if( is_equal( sales, largest ) ) ++largest_count ;
    else if( sales > largest )
    {
      second_largest = largest ;
      second_largest_count = largest_count ;
      largest = sales ;
      largest_count = 1 ;
    }
    else if( is_equal( sales, second_largest ) ) ++second_largest_count ;
    else if( sales > second_largest )
    {
      second_largest = sales ;
      second_largest_count = 1 ;
    }
  }
  
  cout << "largest: " << largest << " occurs " << largest_count
       << "times\nsecond largest: " << second_largest << " occurs "
       << second_largest_count << "times\n" ;
}
vijayan121 1,152 Posting Virtuoso

boost::filesystem library provides portable facilities to query and manipulate paths, files, and directories.
it supports operating systems which provide either the POSIX or Windows API and is in regular use on a number of platforms (including Microsoft Windows and Sun Solaris) using a variety of compilers. programs using the library are portable, both in the syntax and the semantics of program code.

tr2 has a proposal to add a filesystem library component to the C++ Standard Library. this proposal is based on boost::filesystem. http://www.boost.org/libs/filesystem/doc/tr2_proposal.html#Introduction

unlike most of boost, this is not a header only library. (much of the library code is platform specific. the right code is chosen based on the platform settings when building.)

here is how you could use the library to get the last modified time for a file.

#include <boost/filesystem/operations.hpp>
#include <ctime>
#include <iostream>
#include <fstream>

int main()
{
  boost::filesystem::path path( 
                    "/usr/local/include/boost/filesystem/operations.hpp" ) ;
  std::time_t t = boost::filesystem::last_write_time( path ) ;
  std::cout << "UTC: " << std::asctime( std::gmtime(&t) ) ;
  // note: some file system report last write time as local time, 
  // while others (eg. NTFS) report it as UTC. this can be checked 
  // by creating a new file and getting it's timestamp. eg.
  path = "/tmp/test_file" ;
  {
    std::ofstream file( path.file_string().c_str() );
    file << "test\n" ;
  }
  t = boost::filesystem::last_write_time( path ) ;
  std::cout << "just created UTC: " << std::asctime( std::gmtime(&t) ) ;
}
/**
>c++ -L/usr/local/lib -lboost_filesystem filesystem.cc && ./a.out
UTC: Tue Aug 14 …
vijayan121 1,152 Posting Virtuoso
#include <sstream>
#include <iostream>

int main()
{
  std::string line = "how now brown cow" ;
  std::istringstream stm(line) ;
  std::string str ;
  while( stm >> str ) std::cout << str << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

you need to read in a complete line at one time ( use std::getline ) and then extract the information from it. a simple way would be to use a std::istringstream

the format of your text file is not well thought out. the simplest would be to leave an empty line (containing only a '\n') after information for each student. that way, you only need to check for an empty string.

if that is not possible, you could do this: if the line you have read contains five whitespace delimited strings, then it is student information; if there are only four, it is course information. you can easily see why this would break if additional fields need to be added later.

vijayan121 1,152 Posting Virtuoso

in c++,
a. you cannot pass an array to a function, only the address of it's first element. the number of elements has to be passed seperately.
b. the name of a function can not be used as a variable
c. return is a statement, not a variable. you need to use return result ; not return = result ;
d. the expression you are testing in an if statement needs to be within paranthesis ( )
are you a pascal programmer?

#include<iostream>
using namespace std;

int smallestnumberindex( const int number[], int index ) ;

int main()
{
  const int N = 10 ;
  int number[N];
  int index;

  //input data
  cout << "Enter " << N << " integers " << endl;
  for (index = 0; index < N; index++)
    cin >> number[index];
  // print array
  for (index = 0; index < N; index++)
    cout << number[index] << "  ";

  cout << "The smallest index is " << smallestnumberindex( number, N )  << endl;
}

int smallestnumberindex( const int number[], int N )
{
    int smallest = 0;
    int index;
    for (index = 1; index < N; index++ )
    {
      if( number[index] < number[smallest] )
        smallest = index;
    }
    return smallest ;
}
vijayan121 1,152 Posting Virtuoso

> ... but getline can't be used with integers ...
it is easier to process each element in your image as a char rather than an int. eg.

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

struct replace_chars
{
  string operator() ( const string& str ) const
  {
    string result = str ;
    for( size_t i=0 ; i<result.size() ; ++i )
    {
      switch( result[i] )
      {
        case '0' : result[i] = ' ' ; break ;
        case '1' : result[i] = '-' ; break ;
        case '2' : result[i] = '=' ; break ;
        case '3' : result[i] = 'O' ; break ;
        // etc
      }
    }
    return result ;
 }
};

int main()
{
  string filename ;
  getline( cin, filename ) ;
  ifstream file( filename.c_str() ) ;
  size_t rows, cols ;
  file >> rows >> cols >> ws ; // skip over white spaces
  assert( rows>0 && cols>0 ) ;
  vector< string > image ;
  const string digits = "0123456789" ;
  string line ;
  while( getline( file, line ) && ( image.size() < rows ) )
  {
    assert( line.size() == cols ) ;
    assert( line.find_first_not_of(digits) == string::npos ) ;
    image.push_back( line ) ;
  }
  assert( image.size() == rows ) ;
  transform( image.begin(), image.end(),
             ostream_iterator<string>(cout,"\n"),
             replace_chars() ) ;
}
vijayan121 1,152 Posting Virtuoso

remove the #include of the resource script from your main.cpp

//main.cpp
#include <windows.h>
#include "resource.h"
 //#include "Untitled.rc"
// ...
vijayan121 1,152 Posting Virtuoso

> when i type in a char, they straight away have a infinite loop. I try using the cin.clear() ...
the problem is that there is some char(s) left in the input buffer which gave the error earlier and will continue to give errors till you remove it (them). eg.

int num = 0 ;
  while( !(cin>>num) )
  {
    cin.clear() ;
    char c ;
    cin >> c >> ws ;
  }
  cout << num << '\n' ;

for more details, search this forum for a thread which has 'flush input buffer narue'

vijayan121 1,152 Posting Virtuoso

here is something obtained thru googling (i've no clue about either dev-c++ or sdl); see if these help.
http://www.gpwiki.org/index.php/C:How_to_set_up_your_SDL_Build_Environment#Windows:_Dev-C.2B.2B
http://www.imrtechnology.ngemu.com/sdldevtut.htm
if they do not, abandon daniweb and try a forum where there may be people who are more knowledgable. eg. http://gpwiki.org/forums/viewforum.php?f=2

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

int main()
{
  int counter = 0 ;
  int sum = 0 ;
  const int limit = 7 ;

  int num_days = 0 ;
  while( counter < limit )
    {
      int number ;
      cin >> number ;
      if (number > 0)
      {
        sum = sum + number;
        num_days = num_days + 1;
      }
      counter = counter + 1 ;
    }
    
  cout << "The total minutes excersized is " << sum << endl;
  if( num_days > 0 )
  {
    cout << "The average minutes excersized per day during this week is "
          << double(sum) / counter << endl;
    cout << "The number of days excercised is " << num_days << endl;
  }  
} 
/**
>c++ exersize.cc && ./a.out
1 0 2 3 4 0 5
The total minutes excersized is 15
The average minutes excersized per day during this week is 2.14286
The number of days excercised is 5
*/
vijayan121 1,152 Posting Virtuoso

you need to accept seven integers from the user; so you need to move cin >> number; to inside the while loop that executes seven times.

counter is initially zero; so to execute the loop seven times, you should write while (counter < 7) // not <=

vijayan121 1,152 Posting Virtuoso

in addition, this expression sum / counter will do integer division; ie. if sum ==23 and counter==7, the result would be 3, not 3.28. you could either make sum a double or write double(sum) / counter to get the fractional part.

it is also a good idea to get into the habit of initializing a variable at the point of definition; this will protect you from silly errors (using uninitialized variables) and later, when you deal with more complex types, help you write more efficient code. ie. not

int counter;
	int sum;
	int limit;
	limit = 7;
	sum = 0;		
	counter = 0;

but

int counter = 0 ;
	int sum = 0 ;
	int limit = 7 ;

also, since limit is a constant, declare it as such eg const int limit = 7 ; or enum { limit = 7 } ; how you write code later is going to be determined to a large extent by the habits you form in the early days; forming good habits now (some people call this programming hygiene) would serve you well in the future,

vijayan121 1,152 Posting Virtuoso

here is a very old game, which requires only text input or output, is simple, and is interesting to program. http://en.wikipedia.org/wiki/Nim

vijayan121 1,152 Posting Virtuoso

(most) windows programs are written to run against an environment subsystem. the subsystem is specified in the PE header of the executable image and is placed there by the linker.
currently, your program is being linked with the linker switch /SUBSYSTEM:WINDOWS. this implies that your program does not require a console, probably because it creates its own windows for interaction with the user. if you do not specify an entry point for your executable (where the program should start executing) by using the /ENTRY linker switch, the linker inserts a suitable default. for /SUBSYSTEM:WINDOWS, this is WinMainCRTStartup (or wWinMainCRTStartup) which after initializing the C runtime library will call WinMain (or wWinMain).
since you are writing a console based program, you need to change the linker switch to /SUBSYSTEM:CONSOLE. this specifies that your program is a Win32 character-mode application and needs to be given given a console on startup. the defaul;t entry point would now be mainCRTStartup (or wmainCRTStartup) which after initializing the C runtime library will call main (or wmain).
to modify this linker option in the vc++8 ide: Project->Properties->Linker->System->Subsystem
for more information: http://msdn2.microsoft.com/en-us/library/fcc1zstk(vs.71).aspx
http://msdn2.microsoft.com/en-us/library/f9t8842e(VS.71).aspx
note: this is really not a c++ question, c++ only talks about main,

vijayan121 1,152 Posting Virtuoso

> my variable 'advance', is a ambiguous symbol and cannot be used....why?
the c++ standard library defines a function std::advance (header <iterator> ; the function is used to move an iterator by a certain distance). your program would be (indirectly) including this header and also has a using namespace std ; directive. if you also define a variable at global scope with the name advance, the unqualified reference to identifier 'advance' becomes ambiguous.

> after i change the 'advance' to other word, like 'advanced', it run nicely....
after you change the name, the name clash is no longer there.
you can also get rid of the ambiguity by moving the definition of the variable advance from global scope to inside (the local scope of) main.
another way is to always specify the fully qualified name for advance; std::advance for the standard library function and ::advance for your (global) variable.
yet another solution would be to remove the using directive using namespace std ; and instead have using declarations eg.

using std::cin ;
using std::cout ;
using std::endl ;
vijayan121 1,152 Posting Virtuoso

> I would just like to know how to get the ASCII code number after inputing an ASCII character.
a. change the locale of std::cin from the default locale to one using an ASCII char set.
b. read the char entered by the user
c. convert it to an int to get the ascii code point.
d. use the tolower member of the ctype facet of the locale imbued by std::cin to get the lower case character
or check for the code point to be in the range for upper case chars; add 32 to get the lower case char (works for ascii)

vijayan121 1,152 Posting Virtuoso
// ...
TwoD m1 ( d1 , d2 ) ;
// ...
cin >> m1 ( k , j ) ;
// ...

for this to work, the class TwoD should provide an overloaded function call operator that can take k and j as args. and would return a reference to the 2d array element at k,j as a modifiable l-value. eg.

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

class TwoD
{
  public:
        // ...
        TwoD ( int nrows, int ncols ) : d1(nrows), d2(ncols)
        {
          assert( d1>0 && d2>0 ) ;
          m = new int[ d1 * d2 ] ;
        }
        int operator() ( int i, int j ) const
        { assert( i<d1 && j<d2 ) ; return ( m + i*d2 )[j] ; }
        int& operator() ( int i, int j )
        {  assert( i<d1 && j<d2 ) ; return ( m + i*d2 )[j] ; }
        // ...
  private:
        int *m ;
        int d1 ;
        int d2 ;
};

using a function call operator to access array elements would not be intuitive to most c++ programmers; overloading the array subscript operator would make the use of TwoD easier. eg.

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

class TwoD
{
  public:
        // ... ;
        TwoD ( int nrows, int ncols ) : d1(nrows), d2(ncols)
        {
          assert( d1>0 && d2>0 ) ;
          m = new int[ d1 * d2 ] ;
        }
        struct row ;
        const row operator[] ( int i ) const
        { …
ndeniche commented: precise!!! :D +3
vijayan121 1,152 Posting Virtuoso

>> what function which is similar to stat that asks for a FILE* fildes rather than int fildes?
the function [B]int fileno(FILE *stream);[/B] is part of both posix and single unix specifications. http://www.opengroup.org/onlinepubs/009695399/functions/fileno.html
this would give the file descriptor using which you can call fstat() which also conforms to posix.

jaepi commented: Exactly what I need. +2
vijayan121 1,152 Posting Virtuoso

>> how I can use "explicit template instantiation" in the above example.
an explicit instantiation directive consists of the keyword template followed by a declaration of the version to be instantiated. for example,

template std::string CTClass< std::string >::add() ;

is an explicit intantiation of the member function.
all the members of a class template can be explicitly instantiated by explicitly instantiating the class template. eg.

template class CTClass< double > ;

>> why would I use "explicit template instantiation" ?
there are two valid reasons:
a. while writing/testing template code, it is a good idea to explicitly instantiate the template you have written for a few types. unless a template is instantiated, some errors which are present in the template code may not be detected by the compiler.
b. when there is a large code base with a number of templated types, automatic template instantiation in multiuple translation units can increase build times. manually instantiating certain template specializations in a single location and inhibiting the instantiation in all other translation units can mitigate this.

a third reason is that many (most) compilers do not support the export of templates; if we know that only a few versions of a template are required, we can work around this limitation by explicitly instantiating the template in the translation unit where it is defined and only declaring it in other translation units. however, this assumes that the decorated (mangled) names for an explicitly instantiated template …

vijayan121 1,152 Posting Virtuoso

perhaps this would clarify (not different, but the types involved are simpler and therefore the example is easier to follow).

void foobar( int a, int b ) {}

int main()
{
  int a = 78 ;
  int foo( int(a) ) ; // is this the declaration (of a function foo)
                      // or the definition of an int foo?
  int(*pfn)(int) = &foo ; // it is a declaration!

  int bar( (int(a)) ) ; // can't be the declaration (of a function bar)
  int* pi = &bar ; // so, must be the definition of an int bar
  // reason (int(a)) is an expression because of parantheses; 

  // for example
  foobar( a, bar ) ; // ok
  // foobar( (a, bar) ) ; // error, too few arguments to function foobar
                       // because (a,bar) is *a single* expression
}

int foo( int(a) )
{
  return a+6 ;
}

there are several threads in comp.std.c++ which discuss why the language rules are framed this way, what would have been the alternatives etc. here is one of them http://groups.google.com/group/comp.std.c++/browse_thread/thread/57b52b0a1a40a9ad

n.aggel commented: thanks for the example +1
vijayan121 1,152 Posting Virtuoso

> im having a problem on how to use the NCURSES... I have problems on compiling it... Too many errors...
> Im using Dev C++ compiler..
a bit of searching the web reveales that there is a Dev-C++ DevPak for pdcurses.
pdcurses is another implementation of curses; therefore you could use it instead.
the download: http://sourceforge.net/project/showfiles.php?group_id=94270&package_id=154278&release_id=515268
i do not use Dev-C++ nor do i know about Dev-C++ DevPaks; so i do not know what are the things you have to do after downloading it to get it working. but i guess there must be an easy way to do it.

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

switch (randNumGen2) randNumGen2 is not an integral expression and can not be used in a switch.
did you intend switch[B][B]( [/B][/B]randNumGen2->Next(1,5)[B][B] )[/B][/B] ?

vijayan121 1,152 Posting Virtuoso

the code that you posted originally will not compile (line 16 has a typo).
> the last set of statements {also compiles} but it prints this � character...
the most likely cause is that the iterator pos == coll.end() when you dereferenced it.

vijayan121 1,152 Posting Virtuoso

> i declared a variable 'va'
> in c++ code ..the value of va changes based upon
> the input given by user which is done many times in program
> and i like to print the value of va many times in program
> but,only after the user is satisfies with his number of inputs
> so i need to output all the values va all at a time at the only at the end

this was your original problem. and dragon gave you a couple of reasonable solutions. all your questions about flush and stream buffers have been taking you farther away from a solution to the actual problem that you are facing.
a. narue informed you that flushing of the stream does happen automatically even if you do not call flush.
b. setting the buffer size to a large value by something like char buf[1024*128] ; cout.rdbuf()->pubsetbuf(buf,sizeof(buf)); does not guarantee that the stream will not get flushed. the c++ standard only defines the behavior of pubsetbuf(0,0); this has the effect of turning off any buffering. pubsetbuf() called with any other values may or may not change the flushing behavior of the stream.
usually, calls to pubsetbuf() with non-zero values modify the flushing behaviour for filebufs (used with file streams). the specific behavior has to be defined in the documentation of the implementation (it is "implementation defined"). and you could look this up in the documentation provided by the specific implementation …

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


template< size_t PAD, size_t NBITS > inline
bitset<NBITS+PAD> pad_msb0( const bitset<NBITS>& bs )
{ return bitset<NBITS+PAD>( bs.to_string() ) ; }

template< size_t PAD, size_t NBITS > inline
 bitset<NBITS+PAD> pad_lsb0( const bitset< NBITS >& bs )
{ return pad_msb0<PAD>(bs) << PAD ; }

// if we want to pad with bit of 1 instead of 0
template< size_t PAD, size_t NBITS > inline
 bitset<NBITS+PAD> pad_msb1( const bitset< NBITS >& bs )
{ return bitset<NBITS+PAD>( string(PAD,'1') + bs.to_string() ) ; }

// if we want to pad with bit of 1 instead of 0
template< size_t PAD, size_t NBITS > inline
 bitset<NBITS+PAD> pad_lsb1( const bitset< NBITS >& bs )
{ return bitset<NBITS+PAD>( bs.to_string() + string(PAD,'1') ) ; }

int main()
{
 enum
 {
   NBITS = 21,
   DIGITS = numeric_limits<unsigned long>::digits,
   WIDTH = DIGITS/4 + 2
 };
 bitset<NBITS> bits( string("10101010111") ) ;
 cout << hex << showbase << internal
      << bits << ' '
      << setw(WIDTH) << setfill('0') << bits.to_ulong() << '\n'
      // > ...the code gives error of...
      // you must be using an old compiler; NBITS should be deduced.
      // if that is the only issue with the compiler, specifying the
      // template parameter explicitly would fix it. ie.
      // istead of pad_msb0<5>(bits), use pad_msb0<5,NBITS>(bits) eg.
      << pad_msb0<5,NBITS>(bits) << ' '
      << setw(WIDTH) << setfill('0')
      // > ...output of pad_msb function as bits and not as string...
      // if the number of bits can be held …
vijayan121 1,152 Posting Virtuoso

> ........increasing the capacity that the buffer can hold
lookup std::basic_ios<>::rdbuf and std::basic_streambuf<>::pubsetbuf

> .........by "removing any ties" that the ostream object has
calling std::basic_ios<>::tie(0) will remove any tie.

vijayan121 1,152 Posting Virtuoso
class GBook
{
      // ...
      void inputGrades( int& ,int&, int& );
      // ....
      void displayReport( int course_number ) ;
      // ...
};
// ...
void GBook::inputGrades( int& x1, int& x2, int& x3 )
{
  // ...
}
// ...
void GBook::displayReport( int course_number )
{
   setCourseNo( course_number );
   displayMsg();
   int x1, x2, x3 ;
   inputGrades(x1,x2,x3);
   MaxValue = max(x1,x2,x3);
   cout << "max: " << MaxValue << '\n' ;
}
// ...
int main()
{
   GBook book;
   int cn ;
   cout << "course no.: " ;
   cin >> cn ;
   book.displayReport( cn ) ;
}
vijayan121 1,152 Posting Virtuoso

> ..default input is other than decimal? is this possible?
yes, look up ios_base::fmtflags

> if i add cin.clear() i don't get any different behaviour...what is the difference?
clear() merely sets sets the state to a good state. if the stream is already in a good state, there would be no difference. if the stream is not in a good state, it would make a difference

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

int main()
{
  string input = "0101 \n 0101 \n 0101 \n *&^%$ \n 0101 \n" ;
  istringstream stm(input) ;
  streambuf* buff = cin.rdbuf( stm.rdbuf() ) ;
  
  int i ;
  cin >> i ;
  cout << "default input (decimal): " << i << '\n' ;
  cin >> oct >> i ; cout << "octal input: " << i << '\n' ;
  cin >> hex >> i ; cout << "hex input: " << i << '\n' ;
  cin >> dec >> i ; // fails, cin is now not in a good state
  assert( !cin ) ; // next char in buffer is '*'
  cin.clear() ; // reset the state of cin to good
  cout << "next char in input is: '" << char( cin.peek() ) << "'\n" ;
  cin.ignore(100,'\n') ; // remove chars (max 100) upto next newline
  cout << "next char in input is: '" << char( cin.peek() ) << "'\n" ;
  assert( cin >> dec >> i ) ; // ok
  cout << "decimal input: …
vijayan121 1,152 Posting Virtuoso
#include <iostream>
using namespace std ;

// is every decimal digit of number a 0 or 1
bool is_every_digit_zero_or_one( unsigned int number )
{
  while( number > 0U )
  {
    if( number%10U > 1U )return false ;
    number /= 10U ;
  }
  return true ;
}

// read in an unsigned int containing only decimal digits 0 and 1
// user should get stuck entering a "binary" integer if the value
// entered is not of the right form
unsigned int read_in_number()
{
  unsigned int number ;
  // cin >> skipws >> dec ; // being safe, ignore this for now
  do
  {
    cout << "number? " ;
    // also ignore cin.clear/cin.ignore; by spec. user should get 'stuck'!
    cin >> number ;
  }while( !is_every_digit_zero_or_one( number ) ) ;
  
  return number ;
}

int main()
{
  unsigned int n = read_in_number() ;
  cout << "number (binary digits; leading zeroes omitted): " << n << '\n' ;
  // 'convert' number to decimal, and print out the value
}
vijayan121 1,152 Posting Virtuoso

a. you do not need a sentinal node (with the value "INVALID") at the beginning of the list
b. if the value you are trying to insert compares less than the value in a node, you need to insert *before* not after the node
c. in more than one place, you are forgetting to initialize/modify values

// ...
// ...
class List
{
  public:
      List()
      {
          cout << "Creating a new list..." << endl;
          /* *** removed, no need for sentinal node
              top = new Node;
              top->value = "INVALID";
              top->next = NULL;
          */
          top = NULL ; // *** added
          end = NULL;
          count = 0;
      }
      // ...
     // ...
      void SortInsert(string data)
      {
          Node *tmp = new Node;
          Node *prev = NULL;
          // Node *x = top->next; // ***  removed, no sentinal node

          tmp->value = data ;  // *** added
          tmp->next = NULL;
          Node* x = top; // *** modified

          if (x == NULL)
          {
            top = end = tmp; // *** modified
            ++count ; // *** added
          }
          else
          {
            while (x != NULL)
            {
              if (data < x->value)  // THIS STATEMENT
              {
                // *** modified as data<x->value, add *before* not after x
                //tmp->value = data;  // *** removed
                tmp->next = x ; // *** modified
                if( prev != NULL ) prev->next = tmp; // *** modified
                else top = tmp ; // *** modified
                count ++;
                break;
              }
              else if (x->next == NULL)
              {
                x->next = tmp;
                end = tmp ; // *** …
vijayan121 1,152 Posting Virtuoso

> I wonder what the stl actually is, and what it's useful for.
see http://en.wikipedia.org/wiki/Standard_Template_Library

> I thought that the standard template library was the library of all standard functions for all common C++ areas
stl is a subset of the C++ standard library, and provides containers, algorithms, iterators, function objects, generic strings etc. the other important pars of the standard c++ library are streams and i/o, numerics, language support and the iso C standard library. currently, the stl portion constitutes roughly one third of the c++ standard library.

> I need a good reference regarding file i/o objects and syntax so that I don't have to keep switching ...a reference that will help me now with streams and file I/O, and help me later with linked lists and other advanced C++ topics.
The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis does have introductory tratment of stream classes, stream manipulators and formatting, file I/O, internationalization, and locales. and would be more than adequate for all your immediate requirements.

vijayan121 1,152 Posting Virtuoso

> Would this be a comprehensive reference, listing and describing all the standard parts of file i/o, objects etc
this book explains the stl part of the standard library very well. very good for learning that part of the c++ library and would be a handy reference later.

however, if your primary interest is in learning about the iostream library, this is perhaps not the ideal book.
Standard C++ IOStreams and Locales: Advanced Programmer's Guide and Referenceby Angelica Langer and Klaus Kreft (Addison-Wesley Professional) would be what you are looking for.

each of these books cover different parts of the standard library.

> have there been any significant changes that would make parts of it outdated?
no, there is nothing that could be called a *significant* change. however, there are additions proposed in the upcomming c++0x standard; the ones already accepted (TR1) are covered in
The C++ Standard Library Extensions: A Tutorial and Reference By Pete Becker (Addison Wesley Professional)
TR1 almost doubles the size of C++ standard library; so there are a lot of things here as well.

vijayan121 1,152 Posting Virtuoso

according to the c++ standard, this is how:
header file (abc.h):

#ifndef _ABC_H
#define _ABC_H
namespace my
{
  export template< typename T > struct abc
  {
    explicit abc( const T& val = T() ) ;
    const T& value() const ;
    template< typename other > void foo( const other& x ) ;
    private: T _value ;
  };
}
#endif // _ABC_H

the implementation file (abc.cc):

#include "abc.h"

namespace my
{
  export template< typename T > abc<T>::abc( const T& val ) : _value(val)
  {
    /* .... */
  }

  export template< typename T >  const T& abc<T>::value() const
  {
    return _value ;
  }
  export template< typename T >
    template< typename other > void abc<T>::foo( const other& x )
    {
       /* .... */
    }
}

however, most current c++ compilers do not support export of templates ( comeau c++ (EDG) is the only one that i know of that does support this http://www.comeaucomputing.com/4.0/docs/userman/export.html ). for example this is the result of trying to compile this with gcc 4.2.2 (release candidate)
>g++42 -Wall -std=c++98 main.cc abc.cc

In file included from main.cc:1:
abc.h:5: warning: keyword 'export' not implemented, and will be ignored
In file included from abc.cc:1:
abc.h:5: warning: keyword 'export' not implemented, and will be ignored
abc.cc:5: warning: keyword 'export' not implemented, and will be ignored
abc.cc:10: warning: keyword 'export' not implemented, and will be ignored
abc.cc:14: warning: keyword 'export' not implemented, and will be ignored

vijayan121 1,152 Posting Virtuoso

> I'm not that desperate yet. I do have some solutions...
i'm quite relieved. i was not happy about about it after having impulsively made that post; it is not something that should be used.

vijayan121 1,152 Posting Virtuoso
template< typename T >
class A
{
  // ...
    template< typename SEARCH, typename STAT >
      inline void search_s( SEARCH srch, STAT stat )
      {
        // implement here (inline)
        // some compilers complain otherwise.
        // can use the argument srch and stat here
        // ...
      }
  // ...
};
Dave Sinkula commented: I have been lax on giving you the reputation points have deserve. +11
vijayan121 1,152 Posting Virtuoso

> As a general rule that will not work because many languages take up two or more bytes.
yes, it is not a general rule and will not work for any language taking up more than one byte per character. it will only work for single byte encodings (conforming to 'Basic Latin'). in this case, the code points for the equivalent unicode characters are in the range 0x0000 to 0x007f
for example, in ASCII and similar char sets, the code point for a lower case 'c' is 0x63; it would have the same value in a unicode encoding. http://unicode.org/charts/PDF/U0000.pdf
intel's x86 processors use the little-endian format (increasing numeric significance with increasing memory addresses) for data. so, 0x0063 as a two byte value would be stored in memory from lower to higher address as:
-------------------
| 0x63 | 0x00 |
-------------------
and 0x00000063 as a four byte value would be stored in memory from lower to higher address as
-------------------------------------
| 0x63 | 0x00 | 0x00 | 0x00 |
-------------------------------------
for these char sets, for a character string containing atleast two characters, the byte at the address immediately higher than the start address would be non-zero for char, zero for wchar_t.

vijayan121 1,152 Posting Virtuoso

sending data:

// ...
HWND window = ::FindWindow( 0, L"app B's window title" ) ;
if( ::IsWindow(window) )
{
     TCHAR message[] = L"Hello World" ;
     COPYDATASTRUCT data = { 0, sizeof(message), message } ;
     ::SendMessage( window, WM_COPYDATA,
                    WPARAM( 0 /* your window's handle */ ),
                    LPARAM( &data ) ) ;
}
//...

receiving data:
from your code it appears that you are using MFC;
a. in your CMainFrame (the top window) class (mainfrm.h) add,

class CMainFrame : public CFrameWnd
{
  // ...
    afx_msg LRESULT OnCopyData(WPARAM, LPARAM); // *** add this ***
  // ...
};

b. in mainfrm.cpp, add a mesage map entry

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
  // ... other message map entries
  ON_MESSAGE( WM_COPYDATA, OnCopyData ) // *** add this ***
END_MESSAGE_MAP()

c. in mainfrm.cpp, implement the message handler

LRESULT CMainFrame::OnCopyData( WPARAM wParam, LPARAM lParam )
{
  COPYDATASTRUCT* pcds = (COPYDATASTRUCT*)lParam ;
  // use the data
  // eg.
  ::AfxMessageBox( LPCTSTR(pcds->lpData) ) ;
  // if you want to keep the data for later use, you must
  // allocate memory yourself and do a deep copy of the data
  // ...
  return 0 ;
}
vijayan121 1,152 Posting Virtuoso

> Win32 api's are using wchar_t* which is hard for me since most of the standard library are using const char* or char*.
> I've been having a hard time porting these win32 apis to standard library. *sigh*.

most (not all) of the c++ part of the standard library has good support for mutilple character types. for wchar_t characters, you could use wcout (instead of cout), wifstream (instead of ifstream), wstring (instead of string) etc. you would also have to handle C literal escape sequences correctly eg.

void put_newline( std::wofstream& stm )
{
   stm << stm.widen( '\n' ) ; // widen can be used on *all* streams
}

the problem remains in the places where you use the posix api

here is a desperate hack; really desperate, do not use unless you have no other option:

#include <iostream>
#include <cassert>

// *** do not use except as a desperate hack
// ***
// *** invariants:
// *** pointer_to_non_null_cstr *must* point to a c-style string
// *** of char having a length of *atleast two* characters
// *** or of wchar_t having a length of *atleast one* character
// *** char type in use must conform to ISO/IEC 646 encoding (eg. ASCII)
// *** results are *undefined* if any of these are not met
// ***
// *** written for endianess on intel (i386) platform
inline bool is_it_wchar_t( const void* pointer_to_non_null_cstr )
{
  union
  {
    char ch[ sizeof(wchar_t) ] ;
    wchar_t wch ;
  } ;
  wch …
vijayan121 1,152 Posting Virtuoso

use :: SendMessage to a window of application B. and you *must* use a WM_COPYDATA message. eg.

// ...
HWND window = ::FindWindow( 0, L"app B's window title" ) ;
if( IsWindow(window) )
{
     
     TCHAR message[] = L"Hello World" ;
     COPYDATASTRUCT data = { 0, sizeof(message), message } ;
     ::SendMessage( window, WM_COPYDATA, 0 /* your window's handle */, &data ) ;
}
vijayan121 1,152 Posting Virtuoso

>> I don't get it.
!!

#include <iostream>
int main()
{
   int N ;
   std::cout << "Enter Number:" ;
   std::cin >> N ;
   if( N < 1 || N > 10 ) /* ... */ ;
   else std::cout << N * (N+1) / 2 << '\n' ; 
}
vijayan121 1,152 Posting Virtuoso

1 + 2 + 3 + ... + (N-1) + N == N * (N+1) / 2
for M>1, M + (M+1) + ... + (N-1) + N == N * (N+1) / 2 - M * (M-1) / 2

vijayan121 1,152 Posting Virtuoso

#include <functional> and use gcc 4.3 with the switch -std=c++0x

#include <iostream>
#include <functional>
using namespace std;
 
int main(int argc, char * argv[])
{
        hash<const char*> H;
        cout << "foo() ->" << H("foo()") << endl;
}
// g++43 -std=c++0x -Wall -c -g main.cc
vijayan121 1,152 Posting Virtuoso
#include <algorithm>
#include <vector>
#include <iterator>
#include <boost/assign.hpp>
#include <cassert>
#include <iostream>
using namespace std;
using namespace boost::assign;

int main()
{
  vector<int> sequence ;
  sequence += 52, 3, 4, 2, 49 ;
  enum { N = 3 } ;
  assert( sequence.size() >= N ) ;
  vector<int> last_n( sequence.end() - N, sequence.end() ) ;
  sort( last_n.begin(), last_n.end() ) ;
  do
  {
    copy( last_n.begin(), last_n.end(), ostream_iterator<int>(cout," ") ) ;
    cout << '\n' ;
  } while( next_permutation( last_n.begin(), last_n.end() ) ) ;
}
vijayan121 1,152 Posting Virtuoso

if the number of bits and padding are known at compile time:
(if not, you could use boost::dynamic_bitset http://www.boost.org/libs/dynamic_bitset/dynamic_bitset.html )

#include <iostream>
#include<bitset>
#include <string>

template< std::size_t PAD, std::size_t N > inline
std::bitset<  N + PAD > pad_msb( const std::bitset<N>& bs )
{ return std::bitset<  N + PAD >( bs.to_string() ) ; }

template< std::size_t PAD, std::size_t N > inline
std::bitset<  N + PAD > pad_lsb( const std::bitset<N>& bs )
{ return pad_msb<PAD>(bs) << PAD ; }

int main()
{
  std::bitset<41> bits( std::string("10101010101") ) ;
  std::cout << bits << '\n' << pad_msb<5>(bits) << '\n' 
            << pad_lsb<9>(bits) << '\n' ;
}
/** output:  
00000000000000000000000000000010101010101
0000000000000000000000000000000000010101010101
00000000000000000000000000000010101010101000000000
*/
vijayan121 1,152 Posting Virtuoso

> I dont know how to do that ...
i suppose you have not learned about arrays yet. in which case, use your original idea

/*obtain variable nextDigit
(the first digit in the binary number, then the next and so on.)*/
oneDigit=getchar();

of reading one digit at a time. eg.

#include <stdio.h>
#include <limits.h>

int main()
{
  const int MAXBITS = sizeof(int) * CHAR_BIT ;
  unsigned int value = 0 ;
  int n = 0 ;
  printf("Please enter a binary number\n");
  
  for( ; n<MAXBITS ; ++n )
  {
    int ch = getchar() ;
    if( (ch=='0') || (ch=='1') )
    {
      int bit = ch - '0' ;
      value = value*2 + bit ;
    }
    else break ;
  }
  
  printf( "\nvalue: %u\n", value ) ;
  return 0;
}
vijayan121 1,152 Posting Virtuoso
int ch = getchar() ; // reads a char literal '0', '1' etc.
// the integer contains the code point for the literal (depends on the charset)
// to convert it to an integer digit with value 0, 1 etc. 
if( isdigit(ch) )
{
    int digit = ch - '0' ;
    /* use digit */
}
vijayan121 1,152 Posting Virtuoso

>> The usual problem is trying to mix say ... They don't play well together, since a simple cin will leave a newline on the input stream
the solution for this is simple (assuming that you are not interested in leading whitespaces in a line):

char ch ; string str ;
  cin.get(ch) ;
  getline( cin >> ws, str ) ;
  // user enters: X <newline> Hello World <newline>

>>> i do not have the mixing...
in which case you may be using an old compiler (and libstdc++). for example see
http://support.microsoft.com/kb/240015 in vc++6 (vc++7, vc++8 do not have these problems)
http://gcc.gnu.org/bugzilla/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__closed__&product=gcc&content=getline
in g++ mainly 3.2.x or earlier (these have been fixed in later versions).