![]() |
Tutorials > C++ > Basic Output
Introduction
This tutorial will show you how to produce console output in both C and C++. Contents of main.cpp :
Everytime you want to use library functions from C or C++, you need to include
specific header files (.h) to tell the compiler which functions you can use.
The stdlib.h file includes standard C functions. #include <stdlib.h> // for system function #include <stdio.h> // for printf function #include <iostream> // for cout function Many C++ functions and classes (explained later) are contained in what is called a namespace. A namespace is used to separate different functions and classes to prevent name ambiguity. Creating your own namespaces will be explained in a future tutorial. The functions needed for C++ input and output are embedded in the std namespace. Whenever specifying what namespace to use, you must use the using namespace keywords. // namespace containing C++ io functions using namespace std; int main() {
When doing C output, you would use the printf function.
Whenever a function is used, you may have to pass in some parameters. // C Output printf("C Output\n"); printf("\n");
When doing C++ output, you would use the cout object.
Parameters are therefore not used. Objects will be explained more when we cover
classes in a future tutorial. // C++ Output cout << "C++ Output\n"; cout << "More C++ Output" << endl; The next line shows what it would look like if you did not include the using namespace std line. The :: operator is used as a scope operator to access a specific function, object, etc. in a particular namespace.
std::cout << "Even more C++ Output" << std::endl;
The system function is used to run a command that you could normally run in a console window. Try this out by typing pause in a windows console window. The code must be changed in unix to something like the sleep command. system("pause"); return 0; } Congratulations. You now know how to do basic output in both C and C++. Please let me know of any comments you may have : Contact Me
All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005 Read the Disclaimer |
|