FAQ Questions

  1. What is correct: “void main()” or “int main()”?
  2. Should I put “return 0;” at the end of main()?
  3. How do I pause a program?
  4. How do I generate random numbers?
  5. How do I color text?
  6. How do I clear the screen?
  7. What function can end/terminate my program?
  8. What are the differences between structures and classes?
  9. What are the inline functions?
  10. How do I connect to mySQL database?
  11. How do I read/save a file?
  12. What is STL, actually?
  13. Why should I use “using namespace std;”?
  14. I miss a header file. What do I do?
  15. How do I gotoXY?
  16. How do I write ASM code in my C++ program?
  17. Why use private instead of public?
  18. How does setw() work?
  19. How do I see the ASCII code of a char?
  20. How do I convert an integer to a string?
  21. How do I convert a string to an integer?
  22. Which is correct- “const int” or “int const”?
  23. How to create a header file?
  24. How do you type, without what you type, being displayed on the screen?
  25. How do you read what is typed, before ENTER has been pressed?
  26. How do you determine when a key has been pressed?
  27. When to use “->” and when “.” when accessing data members from a class?
  28. What is the difference between using a typedef or a preprocessor macro for a user defined type?
  29. Why does this linked list declaration giving me an error message?
  30. How can I get the current time in a program?
  31. Is char s[3] = “cpp” legal?
  32. I get the following error message “Floating point formats not linked”. What is wrong with the program?
  33. How can I swap two integers in a single line statement?
  34. Why does the call to fopen in the below code fail?
  35. How can I print binary equivalent of a number?
  36. How can I get the current drive of the disk?
  37. How can I get the name of the executing program during its runtime?
  38. What is the difference between memcpy() and memmove()
  39. Which method should I use for scanning strings?
  40. int(a) - (int)a What is the difference?
  41. How do I get the current time and date?
  42. How do I pass a function as parameter?
  43. How to convert a integer to a string (simpler method)

FAQ Answers

Q: What is correct: “void main()” or “int main()”?
A:According to the ANSI/ISO standard, the correct forms are two:

int main() { /* ... */ }
int main(int argc, char* argv[]) { /* … */ }

Even “void main()” will probably compile (depends on the compiler), it is not correct!

Q: Should I put “return 0;” at the end of main()?
A: No. The ANSI/ISO standard states:
“If control reachesthe end of main without encountering a return statement, the effect is that of executing ‘return 0;’ . ”

So, you don’t really need to put it, because your compiler should do it. But even so, most programmers prefer to put it.

Q: How do I pause a program?
A: There are several ways, most of them depending on the OS you use, and/or the compiler you use.

If you want your program to wait the user to press a key, use:

system("PAUSE"); //don't forget to include (or ).

But this is a Windows system call, and it won’t run on non-Windows platform.

The most portable way is:

cin.get(); //this will wait you to press ENTER

If you want your program to pause for some time, the use:

Sleep(1000); //pause for 1000 milliseconds. Include windows.h

Q: How do I generate random numbers?
A: One way to do it, is to use the rand() function from the stdlib.h file. This way:

cout << rand()%x + y; //generate random numbers in the interval [y;x]

Even though, this function will always generate the same sequence of numbers.

The biggest number that the rand() function can produce, is defined into the RAND_MAX constant.

Q: How do I color text?
A:There are many ways, depending on your compiler.

In Dev-C++ and Turbo C++ :
Use following functions defined in conio.h:

settextcolor() // setting text color
settextbackground() //setting text background
cprintf() // coulered printf

In VC++ and Borland C++:

void setcolor(unsigned short color)
{
HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hCon,color);
}

Include windows.h. To use this function: call it, and pass some integer as an argument, or the name of the color (RED, GREEN…).

Q: How do I clear the screen?
A: In Borland’s compiler, you can use the clrscr() function from the conio.h file.
In VC++, there is no built in function. One way to clear the screen is to use system calls:

system("cls"); //include windows.h

But system call won’t be good pick in many situations! So, you can use the function given at the bottom.

If you use another compiler, you may to clear the screen the ways mentioned above. In case it does not work, then read in your compiler’s documentation.

The function…

// clrscr.h
// adapted from
// Vincent Fatica
// vefatica@syr.edu
// Syracuse University Mathematics
// http://barnyard.syr.edu/~vefatica/
// by Shannon Bauman
// August 9, 1998
// clear entire console screen buffer

#ifndef CLRSCR_H
#define CLRSCR_H

int clrscr();

#include "clrscr.cpp"

#endif
-----------------
// clrscr.cpp
// adapted from
// Vincent Fatica
// vefatica@syr.edu
// Syracuse University Mathematics
// http://barnyard.syr.edu/~vefatica/
// by Shannon Bauman
// August 9, 1998
// clear entire console screen buffer

#include
#include
int clrscr()
{
HANDLE hndl = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hndl, &csbi);
DWORD written;
DWORD N = csbi.dwSize.X * csbi.dwCursorPosition.Y +
csbi.dwCursorPosition.X + 1;
COORD curhome = {0,0};

FillConsoleOutputCharacter(hndl, ‘ ‘, N, curhome, &written);
csbi.srWindow.Bottom -= csbi.srWindow.Top;
csbi.srWindow.Top = 0;
SetConsoleWindowInfo(hndl, TRUE, &csbi.srWindow);
SetConsoleCursorPosition(hndl, curhome);
return 0;
}

Q: What function can end/terminate my program?
A: There are several ways, depending on what exactly you want to do.

void exit(int status)
Performs complete C library termination procedures, terminates the process, and exits with the supplied status code.
The “status” argument, can take two values- EXIT_SUCCESS (which represents the value of 0) and EXIT_FAILURE (which represents the value of 1).
The status value is typically set to 0 to indicate a normal exit and set to some other value to indicate an error.

void abort(void)
Prints the message “Abnormal termination program”, and immediately after aborts the process returning an error code (by default is 3). It does not flush any open stream and do not evaluate any atexit function.
The calling process does not receives back control. abort returns the error code 3 to the parent process or the OS.

int atexit ( void (* function) (void) );
Specifies a function to be executed at exit.
The function pointed by function parameter is called when the program terminates normally.
If more than one atexit function is specified calling this, they are all executed in reverse order, that is, the last function specified is the first to be executed at exit.
ANSI standard specifies that up to 32 functions can be prefixed for a single process.
These functions will not receive any parameter when called.

Return Value.
0 is returned if successful, or a non-zero value if an error occurs.

Portability.
Defined in ANSI-C.

Example.

/* atexit example */
#include
#include

void fnExit1 (void)
{
printf ("Exit function 1.\n");
}

void fnExit2 (void)
{
printf ("Exit function 2.\n");
}

int main ()
{
atexit (fnExit1);
atexit (fnExit2);
printf ("Main function.\n");
return 0;
}

Output:
Main function.
Exit function 2.
Exit function 1.

Q: What are the differences between structures and classes?
A: Classes are to C++, and structures are to C, even you can use structures in C++, too. The only difference is that in the class, all members are private by default, and in the struct are public by default.

Q: What are the inline functions?
A:You declare inline function with the keyword inline. An inline function would look that way:

inline my_funct() { .... }

The difference between regular functions and inline functions is that when you call a regular function, the function is invoked, and when you call an inline function, the code in it just gets on the place where it is called. It is as if you have typed the code in the function there.

The advantage of inline function calls is that you avoid the overhead of the function calling, (e.g. loading parameters onto the stack) so you improve the speed of execution, at the expense of increasing the program size
Also, it is an instruction to the compiler and may be ignored. In other words, the compiler is not guaranteed to place the code inline.

Q: How do I connect to mySQL database?
A: The simpliest way to connect to mySQL database is described in the tutorial, written by Vic Cherubini. You can find it bellow:

Purpose

By the end of this tutorial, you should know:

1. How to link the propery library files to compile your project in Visual C++ 6.0.
2. How to connect to a mySQL database.
3. How to retreive data from it.

Lets get started

In order to connect to a mySQL database in C/C++, you will have to download and compile the proper library files. These files are called mySQL++, and can be found here. Download the zip file and unzip it to a temporary folder. Open the lib folder and copy the file mysql++.lib to your compilers Lib or Library directory.

Create a new project in Visual C++ and press Ctrl+F7. Click the Link tab and type in mysql++.lib into the Library text-box.

Copy all of the .h files from the download into your compiler’s Include directory.

Code

Ok, time for the best part, the code. The first lines of code are ones that you will see echoed throughout all of the tutorials. The 2 lines of code include the proper files in order to be able to compile the project. They are:

#include
#include

The several lines are used to #define the database details such as the host, the username, the password, and the database to connect to. Instead of creating 4 char pointers, I use 4 #define’s like so:

#define host "localhost"
#define username "db_username"
#define password "db_password"
#define database "db"

You will have to change the values in the quotes to match the values that fit you. The next line creates a pointer of type MYSQL to the active database connection:

MYSQL *conn;

This program, being as simple as it is, will contain only one user defined function, main() and the rest of the functions used will be from the mySQL++ API (application program interface).

The next lines are ones that we all know and love:

int main()
{

Followed by that, we tell mySQL that are are about to connect with the mysql_init() function. We pass a value of NULL to it because for our purposes, we don’t need to go into it any further:

conn = mysql_init(NULL);

The next step is to actually connect to the database. This is where the conn variable and the host, username, password, and database #define’s are used:

mysql_real_connect(conn,host,username,password,database,0,NULL,0);

The next 3 lines are code that define variables to get a result and row pointer from the database, along with a variable to increment in the loop if there is more than one row returned by the query:

MYSQL_RES *res_set;
MYSQL_ROW row;
unsigned int i;

Finally, we query the database with the following query using the mysql_query() function: “SELECT * FROM users” like so:

mysql_query(conn,"SELECT * FROM users WHERE userid=1");

After querying the result, we need to store the result data in the variable res_set we defined earlier. This is done like so:

res_set = mysql_store_result(conn);

In our example, there will most likely be more than one row returned (i.e., if there are more than one user in the users table of the database). If so, then you need to find how many rows are returned so that you can loop through each one and print the result of each one like so:

unsigned int numrows = mysql_num_rows(res_set);

Finally, we retrive the result using the function mysql_fetch_row() and then print out all of the data in large chunks. This is done like so:

while ((row = mysql_fetch_row(res_set)) != NULL)
{

However, looping through the number of rows returned is useless if you don’t find the number of fields in each row (in this case, they are all the same because the query comes from the same table, but, if the query were produced on the fly (in the while loop), then the function mysql_num_fields() is used to find the number of fields). I hope that makes sense. Here goes:

for (i=0; i < mysql_num_fields(res_set); i++)
{

And finally, after all this time, we print the stuff out using the plain old C standard function printf():

printf("%s\n",row[i] != NULL ? row[i] : “NULL”);
}
}

Last but certainly not least, we close our connection to the database. When there are multiple connects and many users accessing the database at the same time, it is essential that you connect and disconnect as soon as possible, or you can have disasterous results. The final lines of code disconnect from the database and then exit the main() function:

mysql_close(conn);
return 0;
}

Conclusion

Wow! That was pretty cool, huh? This code took me about an hour to whip up and even longer to write the tutorial (the color coding is the hardest part). I really hope that you learned something from this. I know the code could be made a lot better, and I will do that in the future, but hopefully it will be enough to teach you.

To compile the code, in Visual C++, you can press F7. If you have not already made a project, Visual C++ will ask you if you want to make one. Press Yes and continue on!

On the main page, you can download the code from this tutorial in the Downloads section. The file is named file.cpp.

As always, hope this helps.
-Vic

Q: How do I read/save a file?
A: There are many ways to do it. There is a lot to learn about files. Here are just two very simple examples.
Read a file:

#include
int main() {
ifstream OpenFile(”myfile.txt”);
char ch;

while(!OpenFile.eof()) {
OpenFile >> ch;
cout << ch;
}
return 0;
}

Save a file :

#include

int main() {
ofstream SaveFile(”file.txt”);
SaveFile << "Hello World!";
return 0;
}

These are just very simple examples. If you want to learn details and more ways to read/write files, read this tutorial - All About: File I/O in C++

Q: What is STL, actually?
A: The Standard Template Library (STL) is a general-purpose C++ library of algorithms and data structures, originated by Alexander Stepanov and Meng Lee. The STL, based on a concept known as generic programming, is part of the standard ANSI C++ library. The STL is implemented by means of the C++ template mechanism, hence its name. While some aspects of the library are very complex, it can often be applied in a very straightforward way, facilitating reuse of the sophisticated data structures and algorithms it contains.

Q: Why should I use “using namespace std;”?
A: Qualifying an object’s namespace explicitly will help avoid name collisions… which is the whole reason namespace’s exist. It eases large project creation.
Though, in small projects, it doesn’t matter much.
Also, it has no effect what so ever on the compiled executable. There’s no runtime overhead.

But especially about “using namespace std;”, you don’t avoid name collisions at all, because you pull everything from namespace std into the global namespace. So, it is recommended that you don’t use “using namespace std;” but instead, everywhere you need to use something from this namespace, just type:
std
something (for example: std
cout, std::cin and so on)

Q: I miss a header file. What do I do?
A: Most of you think that the header file has all the code you need. In most of the cases, it is not so (with very few exceptions). The header file just points to the .lib (library) file. Have you ever looked at it? If not, just take a look, and you will see that it is mostly #defines and such.
So, it’s difficult to *just get* a header file.
Although, a little search never hurts. Go to google.com and just type the header file name. You should find something useful. If not, try:
+”header_file_name” +download

Q: How do I gotoXY?
A: This code should help:

#include

void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

Q: How do I write ASM code in my C++ program?
A:This is not a standard C++ feature, but most popular compilers provide some mechanism, like

__asm{
...ASM CODE GOES HERE...
}

Refer to your compiler’s manual to see if something like that is available. You should be careful about what registers you are allowed to modify.

You can also write an assembly language file, assemble it to create an object file and link it together with the other object files.

No matter how you do it, assembly language is complete non-portable and there are very few situations where it’s use is justified.

Q: Why use private instead of public?
A: One of the main features of classes is that they allow you to separate interface from implementation. The interface is the public part, while the implementation is private.

This is useful to minimize the dependancy between parts of the code. Imagine that you are working in a project with 50 other people. You write a class which is very useful (a linked list, for instance), so most people use it in their own parts. Now imagine that you would like to make some changes, say to improve performance. If everybody was allowed to use the guts of your class in their parts of the code, you are screwed; you will have to inform everybody of the change so they can update their code accordingly. But if you declared the guts private and provided a clear public interface, you can now transparently make the improvement to your class while keeping the interface untouched and everybody will automatically benefit from it.

This idea is actually older than Object Oriented Programming. It was the main ingredient of “Abstract Data Types”.

Q: How does setw() work?
A: setw() sets the minimum field width. If you don’t understand it, run this simple piece of code and see what happens to the output:

#include
#include
using namespace std;

int main()
{
cout << setw(4) << "123" << endl;
cout << setw(4) << "23" << endl;
cout << setw(4) << "3" << endl;
return 0;
}

Output:
123
23
3

Q: How do I see the ASCII code of a char?
A: This way:

char a;
a = 'd';
cout << int(a) << endl;

Q: How do I convert an integer to a string?
A: The simplest way is to use a stringstream:

#include
#include
#include
using namespace std;

string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}

int main()
{
int i = 127;
string ss = itos(i);
const char* p = ss.c_str();

cout << ss << " " << p << "\n";
}

Q: How do I convert a string to an integer?
A: The easiest way is to use the atoi() function, which can be found in math.h and stdlib.h. This function takes one argument- the string, and returns an integer.

int atoi( const char *string );

Example:

#include
#include // getch()
using namespace std;

int main()
{
char str[4]={49,55,57,’\0′}; //this is the number 179

int number;
number=atoi(str);

cout << number << endl;

return 0;
}

Have in mind:
atoi() is notorious for causing problems and most experienced programmers place it with gets to be removed from the language at the first chance. The problem is in how it handles errors, it’s far better to use strtol() and cast the result to int. Another option is to use sscanf() or stringstreams to read an integer value from a C-string or C++ string to an int variable.

strtol()

Convert strings to a long-integer value.

long strtol( const char *nptr, char **endptr, int base );

strtol returns the value represented in the string nptr, except when the representation would cause an overflow, in which case it returns LONG_MAX or LONG_MIN. strtol returns 0 if no conversion can be performed.

Parameters:

nptr - Null-terminated string to convert
endptr - Pointer to character that stops scan
base - Number base to use

Include stdlib.h in order to use it.

Q: Which is correct- “const int” or “int const”?
A: It’s a matter of style. There is no technical or standard restriction on which one you use. Even though, most programmers prefere “const int” more than “int const”.

Q: How to create a header file?
A: A header file is just text. You can create it with any text editor. It should contain macros and declarations of functions, classes and global variables.

The definition of the functions, classes and global variables should be in one or more modules (one most of the time) that are compiled into object files.

When you want to use your modules from another module, you include the header file and you link your program with the object file(s) described above.
Posted by Alvaro, on forums.cpp-home.com

Q: How do you type, without what you type, being displayed on the screen?
A:

#include
#include // getch()
using namespace std;

int main()
{
int input;
cout << "Enter number: " ;
while ((input = getch()) != '\r')
putchar(' ');
//Now, what you have entered is stored into
// the "input" variable
return 0;
}

Q: How do you read what is typed, before ENTER has been pressed?
A:

#include
#include // getch()
using namespace std;

int main()
{
int keyPress;

cout <<"Enter a number between 1 and 3: ";
keyPress = getch();

switch (keyPress)
{
case '1':
cout << "You entered one!\n";
break;
case '2':
cout << "You entered two!\n";
break;
case '3':
cout << "You entered three!\n";
break;
default:
cout << "Not a number between 1 and 3!\n";
break;
}
return 0;
}

Q: How do you determine when a key has been pressed?
A:

#include
#include
using namespace std;

int main()
{
while(!_kbhit())
{
cout << "Press any key to exit" << endl;
}
return 0;
}

Q: When to use “->” and when “.” when accessing data members from a class?
A: The -> operator is relevant to structures, classes, and unions only. When you create a regular instance of a struct for example, you would do this:

// To create
T var;

// To access
var.item;

The -> operator was added to simply the same type of access on a pointer:

// To create
T *var = new T;

// To access
(*var).item;

// Alternate access for simplicity
// It is equivalent to (*var).item
var->item;

It is just a convenience.

Q: What is the difference between using a typedef or a preprocessor macro for a user defined type?
A: Both typedef and #define can be used to give a new name to user defined data types. The problem arises when we use pointer-type data types.
Typedefs are preferred because they can correctly encode pointer types. Consider the following statements.

typedef char *string_t;
#define char *string_d

string_t s1,s2;
string_d s3,s4;

In the above declarations, s1,s2 and s3 are all declared as char * but s4 is declared as a char, which is probably not the intention.
The advantage with preprocessor macros is that #ifdef works on them. On the other hand, typedefs have the advantage that they obey scope rules.(that is they can be declared local to a function or a block).

Q: Why does this linked list declaration giving me an error message?
A:

typedef struct
{
char *item;
NODEPTR next;
} *NODEPTR;

How can I overcome this problem?

Answer:
A typedef declaration can’t be used until it is defined, and in the fragment given, it is not yet defined at the point where the next field is declared.
To fix this code, first give the structure a tag “struct node”. Then declare the next field as a simple struct node *, or disentangle the typedef declaration from the structure definition or both.

typedef struct node
{
char *item;
struct node *next;
}*NODEPTR;

typedef struct node *NODEPTR;

struct node
{
char *item;
NODEPTR next;
};

You are permitted to declare a new typedef name involving struct node even though struct node has not been completely defined yet.
The simplest declaration:

struct node
{
char *item;
struct node *next;
}
typedef struct node *NODEPTR;

Q: How can I get the current time in a program?
A:Use the following code to get the current time.

#include
#include
main()
{
time_t now;
time(&now);
printf(”Its %.24s\n”,ctime(&now));
return 0;
}

Q: Is char s[3] = “cpp” legal?
A: It is perfectly legal in ANSI-C but is useful only in rare circumstances. It declares a character array of size 3 and initializes with ‘a’, ‘b’, ‘c’, without the ‘\0′ character. Hence it is not a true C string and therefore can’t be used with strcpy(), printf with %s format and other string functions. The better declaration would be to allocate an extra byte for the NULL character or let the compiler count the necessary space required for the string.

char s[4]= “cpp”;

or

char s[]= “cpp”;

Q: I get the following error message “Floating point formats not linked”. What is wrong with the program?
A: When parsing the source file , if the compiler encounters, a reference to the address of a float, it sets a flag to have the linker link in the floating point emulator. A floating point emulator is used to manipulate floating point numbers in runtime of library functions like scanf() and atof() etc. There are some cases in which the reference to the float is a bit obscure and the compiler does not detect the need for the emulator. The most common case is the one which uses scanf() to read a float in an array of structures. This occurs during the initial stages program development. Normally once the program is fully developed, the emulator will be used in such a fashion that the compiler can accurately determine when to link in the emulator.
To force the floating point emulator to be linked into an application, just include the following function in your program.

void FloatLink()
{
float a = 0 , *b = &a;
a = *b;
}

You do not need to call this function, just include it anywhere in your program.

Q: How can I swap two integers in a single line statement?
A: Use xor operator to accomplish this

a^ = b^ = a^ = b;

Thw following code shows you how to swap :

main()
{
int a = 5, b =4;
a^ = b^ = a^ = b;
printf("a = %d b = %d" a,b);
}

Q: Why does the call to fopen in the below code fail?
A:

fopen("c:\newdir\file.dat", "r");

The file you actually requested with the characters \n and \f in its name probably does not exist and is not what you were trying to open!
In order for literal backslashes in a path name to be passed through to fopen (or to any function) correctly, they have to be doubled, so that the first backslash in each pair quotes the second one.

fopen("c:\\newdir\\file.dat", "r");

Alternatively under MS-DOS, it turns out that forward slashes are also accepted as directory separators, so you could use

fopen("c:/newdir/file.dat", "r");

Q: How can I print binary equivalent of a number?
A: The following code prints the binary equivalent of a short number with 16 bits.

main()
{
short int i, num;
num=259;

printf(" The binary equivalent of % d is");

for(i = 0; i < NUM_BITS; i ++)
printf( "% d",( num<}

Q: How can I get the current drive of the disk?
A: Use _getdrive() function .

#include
main()
{
int disk;

disk = _getdrive()+ ‘A’ -1;
printf(”The current drive is %c”, disk);
}

Q: How can I get the name of the executing program during its runtime?
A: You may never need to know the name of the executable during its runtime. The name of the executable with full path is stored in a string

argv[0]

By knowing the executable ile name you can simulate a virus like activity that is, after doing the necessary job you could delete the file using unlink().

#include
main(int argc,char *argv[])
{
/*
do the required thing i.e you can open autoexec.bat file, win.ini file or any other
sensitive file and write to them what you want to do
*/

//now to delete our executable use
unlink(argv[0]);
//You can check the return value of unlink for success or failure
}

Q: What is the difference between memcpy() and memmove()
A: Both memcopy and memmove copy a block of memory from source to destination except for some minor differences.

If the source and destination locations overlap, memcpy makes no guarantee of copying contents successfully whereas memmove does its job perfectly.

Also memcpy is faster than memmove!

Q: Which method should I use for scanning strings?
A:

char string[200];

scanf(”%s”,string);
gets(string);
fgets(string,sizeof(string),stdin);

Answer:
Crudely speaking, all the above three statements accomplish the same thing - Read a string from the keyboard. However the first two methods are dangerous because gets() and scanf(”%s”,string) will not check whether the input string fits into the memory of the string without exceeding array bounds. Hence if you enter a string having more than 200 characters, (in this case 200) memory adjacent to the array’s last element will be over written causing memory over write. However the third method checks for array bounds using the sizeof operator. If we enter a string more than 200 characters (in this case 200) only the first 199 characters will be read and written into the memory. The extra characters will be discarded. The disadvantage ( you may call it a feature ) is that a ‘\n’ will be appended at the end of the string just before the ‘\0′ character. Hence when you try to use strlen with the string it will report 1 more than the actual string length. To avoid this discrepancy, as soon as you input the string using fgets the next statement must be removing the ‘\n’ character by the simple one line code.

string[strlen(string)-1] = ‘\0′;

Q: int(a) - (int)a What is the difference?
A: “int(a)” is the C++ method of constructing a temporary object by calling a constructor. In this case, since the type is a built-in type, it’s the same as a simple typecast.

“(int) a” is a C-style typecast.

Just to confuse you more, you can use a C++ typecast: static_cast(a)

But basically, there is no difference!

Q: How do I get the current time and date?
A: Use the functions in (or time.h if you’re using old headers). Here’s an example:

#include
#include

using namespace std;

int main ()
{
time_t mytime;
struct tm *times;

time (&mytime);
cout << "Current date and time is: " <

times = localtime(&mytime);
cout <<"tm_sec: " <tm_sec < cout <<"tm_min: " <tm_min < cout <<"tm_hour: " <tm_hour < cout <<"tm_mday: " <tm_mday < cout <<"tm_mon: " <tm_mon < cout <<"tm_year: " <tm_year < cout <<"tm_wday: " <tm_wday < cout <<"tm_yday: " <tm_yday < cout <<"tm_isdst: " <tm_isdst <

cout <<"The time is: " <tm_hour <<":"
<tm_min <<":" <tm_sec <

cout <<"The date is: " <tm_mday <<"-"
<tm_mon+1 <<"-" <tm_year+1900 <

cin.get();
return 0;
}

Q: How do I pass a function as parameter?
A: If you want to pass a function to another function then that is done with a function pointer. Like this ….

bool up(int a,int b) {return b < a;}
bool down(int a,int b) {return b>a;}

void sort(int array[],const int size,bool (*comp)(int,int))
{
// sort array of size size using whichever comp function is passed.
}

call like so…

sort(myintarray,myintarraysize,up);

Q: How to convert a integer to a string (simpler method)
A: char *ss;
int num = 40; //this can be anything
sprintf(ss, "%d", num);

Note this also works with real numbers, not just ints.

Tags: , ,

4 Responses to “General questions”

  1. solomon Hutchinson says:

    How do you create a new function?

  2. Dillip says:

    good article!!!

  3. rajasekhar says:

    write a cpp program to eliminate blankspace,commets,tabs in a given file

  4. rajasekhar says:

    waiting for reply…………..

Leave a Reply

You must be logged in to post a comment.