C++ FAQ

C vs C++?
C++ is based on C, except C++ allows object-oriented programming. If you have a C++ compiler then you can compile most cprograms and mix the two. C++ is kind of like a "newer version" of C. Most C programs are valid C++ programs (but not all of them), not every C++ program is a valid C program. I'm putting this in laymans terms but i think you get the idea. Some differences are that iostream.h cannot be used in C, & there is no cout & cin.


#include <iostream.h>// for C++ method

#include <stdio.h> //for C method

When I try to input in a person's name it only reads in the first name. Why?
If your trying to enter both a first and last name in the one string, what is happening is that "cin" is seeing the first white space/delimiter and assuming this is the end of your string, and this is all that is being written to your file. You might want to consider using the "getline()" as an option.


int main() or void main()?
It's always better to use int main() since some operating systems such as UNIX do not support void main. All compilers are required to accept int main(), because that's what the Standard definition of C says main() should be. It's not a question of whether your operating system "supports" it, it's a question of whether your compiler accepts it. Steve Summit says, "The two compilers I can think of off the top of my head that complain about void main() are DEC's VMS C compiler, and newer versions of gcc (which is of course what djgpp is derived from)".


Is there a way to test for multiple cases in a switch?
If you don't put a break statement in a case, the program will execute subsequent cases until a break is found: (example)


case 'a':
case 'A': cout << "hello"; break;

How do I open a text file?


//by Bolivia454
#include <iostream.h>
#include <fstream.h>

int main()
{
  char buff;           //dim buffr as string
  ifstream iFile;    //input file stream(ifstream)
  iFile.open("filename");   //Open "C:\file.txt" for input as #1
  if (iFile){
    while(!iFile.eof()){   //do while not eof(1)
      iFile >> buff;       //  input #1, buffr
      cout << buff;       //  print buffr
    }    //loop
  }
    else 
      cout << "couldn't open file";
  return 0;}

How do I get the Keyboard code for ____?


//by IKoulchine
void PrintCode()
{
char mychar=getch();
if (mychar=='\0')
	{
	cout << "Extended character!\n";
	mychar=getch();
	}
cout >> "Key code: " << int(mychar) << endl;
}

Arrow keys are part of the extended charset. If one of those keys was hit, here's what happens: the first time you call getch() it returns 0. the next time you call getch() it returns the extended charcode(even if there were no other keyhits).


Random number generator?
In C++ there is no keyword for random numbers, but there is a function in stdlib.h that you can use. It's called rand(). NOTE: rand produces a psuedo-random number, so if produces the same numbers over and over (good for testing). srand() "seeds" rand so that it doesn't start with the same sequence each time. NOTE: randomize() is not a standard function, its one Borland made, so its not portable!

rand() produces a random number between 0 and RAND_MAX, where RAND_MAX is a constant #defined in <stdlib.h>. Or you could use this function:


inline void randomize()
{
srand((unsigned)time(NULL));
}

How do I send something to the printer in MS-DOS?


#include <stdio.h>
int main(void)
{
fprintf(stdprn, "Test"); // Send "Test" to the printer 
return 0;
}

Miscellaneous Stuff

Need to find 1+2+3+...+(n-1)+n?


sum = n*(n+1)/2; 

Prime numbers


int is_prime(int c)
{
	int a,b,index[c]; 
/*a and b counters, index a list of numbers 
that _could be_ factors of c*/
	if(c<=1)return 0;
/*you might want to place a c=abs(c) before this line, 
but thats your decision*/
	for(a=0;a < c;a++)
		index[a]=1;
/*initialize all numers to 0 (potential factors)
note: you could just do index[c-2]
 because 0 and 1 aren't used anyway; 
youd also have to change all references 
to index[n] to index[n-2]*/
	for(a=2;a<c;)
	{
		if(!(c%a))return 0;
/*if a divides c, then c isn't prime*/
		for(b=1;b<=(int)(c/a);b++)
			index[b*a]=0;
/*if a doesn't divide c, 
then neither do any multiples of a*/
		while(!index[a])a++;
/*find another value for a that is a potential factor*/
	}
	return 1;
/*if no numbers 2 through (c-1) divide c, 
then c is prime*/
}

Shuffle a deck of cards


#include <iostream.h>
#include <stdlib.h>
int main()
{
randomize();
int deck[52];
int count = 0;
for( int repeat = 0; repeat < 10000 ; repeat++ ){
for( int card = 0; card < 52; card++)deck[card] = card;
int r,temp;
// ********* Here's my version
/*for( int card = 51; card > 1; card-- )
{
   r = rand()% card;
   // swap
   temp = deck[r];
   deck[r] = deck[card];
   deck[card] = temp;
}  */

// ********* Black Imps Version
for( int card = 0; card < 52; card ++ )
{
   r = rand()%52;
   temp = deck[r];
   deck[r]=deck[card];
   deck[card] = temp;
}
//for( int card = 0; card < 52; card++ ) 
//cout << deck[card] << ' ';
//cout << endl << endl;
if (deck[0] == 0) count++;
}
cout << count;
cin.get();
return 0;
}

How do I wait for user to hit a key?


//Using SLEEP is stupid.
#include <conio.h>
#include <iostream.h>

void main()
{
cout << "\nHit any key to continue.";
while ( !kbhit() ); 
// as long as kbhit() returns 0(no key hit), do nothing
cout << "\nContinuing the program...";
}

OR


<conio.h>

int user;
do {user = getch())} while (user == NULL);

I really need to send my output to the printer using borland turbo C++


//by Dempseyart
#include <fstream.h>

void main(void);

void main()
{
	fstream out_file;
	out_file.open("prn",ios::out);    
	//"prn" redirects the output from a file to the printer
	out_file << "Hello World" << '\f';
	out_file.close();
	return;
}

Always finish your output with a \f form feed character or paper will be stuck in you printer!

Setting things up

First, go to linker options, and make sure that you're linking the graphics library. Then #include <graphics.h.> Then you need to initialize the graphics driver.


int gdriver=DETECT, gmode;
initgraph(&gdriver, &gmode, "[path]");

path is the path to the BGI graphics driver(inside the BGI directory). Note that backslashes will have to become doubled or they'll escape the next character and it won't work. (ie "c:\dos" turns into "c:\\dos" ). You can find them in your compiler's subdirectories. If path is null, it'll look in the current directory

Mode X is most definately not mode 13h. Mode 13h uses a linear memory model, that is, you access the memory as if it were one big, long array. Mode X uses a planar memory model, meaning the graphics data is spread out over a series of planes. However, mode X is quite different from the 16 color graphics modes, which are also planar. In mode X there are 4 planes. The first byte of plane 0 holds the color index for the first pixel. The first byte of the second plane holds the index for the second pixel, ect. ect. The fifth pixel on the screen is the second byte of the first plane(that was quite a mouthful). The mode set code for mode X is downright scary if you don't have a firm grasp of assembly language, and an equaly firm grasp of VGA hardware and programming. It involves changing timings and such, as well as unchaining the memory planes and doing all kinds of stuff to various registers. And good grief, I'm not even going to think about writing a sprite blitting function to take four planes into account. If you can find a decent graphics lib that supports mode X, then go for it, it's the best plain VGA mode for animation. But if you can't, I wouldn't mess with it unless you realy know what you're doing. I prefere to stick with 13h myself although that perfect aspect ratio of mode X is realy appealing.

Lutrosis IKoulchin

Thanks to Steve Summit for some clarifications