C++ Programming Code Examples
C++ > Code Snippets Code Examples
Using Command-Line Arguments to Get a Filename
/* Using Command-Line Arguments to Get a Filename */
#include <fstream>
#include <iostream>
using namespace std;
class Animal
{
public:
Animal(int weight,long days):itsWeight(weight),DaysAlive(days){}
~Animal(){}
int GetWeight()const { return itsWeight; }
void SetWeight(int weight) { itsWeight = weight; }
long GetDaysAlive()const { return DaysAlive; }
void SetDaysAlive(long days) { DaysAlive = days; }
private:
int itsWeight;
long DaysAlive;
};
int main(int argc, char *argv[])
{
if (argc != 2)
{
cout << "Usage: " << argv[0] << " <filename>" << endl;
return(1);
}
ofstream fout(argv[1],ios::binary);
if (!fout)
{
cout << "Unable to open " << argv[1] << " for writing.\n";
return(1);
}
Animal Bear(50,100);
fout.write((char*) &Bear,sizeof Bear);
fout.close();
ifstream fin(argv[1],ios::binary);
if (!fin)
{
cout << "Unable to open " << argv[1] << " for reading.\n";
return(1);
}
Animal BearTwo(1,1);
cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;
cout << "BearTwo days: " << BearTwo.GetDaysAlive() << endl;
fin.read((char*) &BearTwo, sizeof BearTwo);
cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;
cout << "BearTwo days: " << BearTwo.GetDaysAlive() << endl;
fin.close();
return 0;
}
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Write block of data. Inserts the first n characters of the array pointed by s into the stream. This function simply copies a block of data, without checking its contents: The array may contain null characters, which are also copied without stopping the copying process. Internally, the function accesses the output sequence by first constructing a sentry object. Then (if good), it inserts character into its associated stream buffer object as if calling its member function sputc until n characters have been written or until an insertion fails (in this case it sets the badbit flag). Finally, it destroys the sentry object before returning.
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. • Default Constructor: A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively. To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is: • ofstream: This data type represents the output file stream and is used to create files and to write information to files. • ifstream: This data type represents the input file stream and is used to read information from files. • fstream: This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
Read block of data. Extracts n characters from the stream and stores them in the array pointed to by s. This function simply copies a block of data, without checking its contents nor appending a null character at the end. If the input sequence runs out of characters to extract (i.e., the end-of-file is reached) before n characters have been successfully read, the array pointed to by s contains all the characters read until that point, and both the eofbit and failbit flags are set for the stream. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc. Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object. Destructors in C++ are members functions in a class that delete an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called etc. Destructors are different from normal member functions as they don't take any argument and don't return anything. Also, destructors have the same name as their class and their name is preceded by a tilde(~).
In this C++ example, we have two functions with "same name" but different number of arguments. Based on how many parameters we pass during Function call "Determines"
Program demonstrates the implementation of Randomized Binary Search Tree. Function to check if tree is empty. And then make the tree logically empty. Functions to insert data.