Topic : Programming in C/C++
Author : Alexander Allain
Page : << Previous 6  Next >>
Go to page :


long"<<endl;  //strlen returns
//the length of the string
  cout<<"Enter your last name:";
  cin.getline(lastname, 50, '\n'); //lastname is also a string
  strcat(name, " ");   //We want to space the two names apart
  strcat(name, lastname);      //Now we put them together, we a space in
//the middle
  cout<<"Your full name is "<<name; //Outputting it all...
  return 0;
}



Lesson 10: C++ File I/O


This is a slightly more advanced topic than what I have covered so far, but I think that it is useful. File I/O is reading from and writing to files. This lesson will only cover text files, that is, files that are composed only of ASCII text.

C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the header file fstream.h. Ifstream handles file input (reading from files), and ofstream handles file output (writing to files). The way to declare an instance of the ifstream or ofstream class is:

ifstream a_file;
//or
ifstream a_file("filename");


The constructor for both classes will actually open the file if you pass the name as an argument. As well, both classes have an open command (a_file.open()) and a close command (a_file.close()). It is generally a good idea to clean up after yourself and close files once you are finished.

The beauty of the C++ method of handling files rests in the simplicity of the actual functions used in basic input and output operations. Because C++ supports overloading operators, it is possible to use << and >> in front of the instance of the class as if it were cout or cin.

For example:
#include <fstream.h>
#include <iostream.h>

int main()
{
  char str[10];  
         //Used later
  ofstream a_file("example.txt");
   //Creates an instance of ofstream, and opens example.txt
  a_file<<"This text will now be inside of example.txt";
   //Outputs to example.txt through a_file
  a_file.close();                          
   //Closes up the file
   ifstream b_file("example.txt");
   //Opens for reading the file
  b_file>>str;    
             //Reads one string from the file
  cout<<str;  
           //Should output 'this'
  b_file.close();    
           //Do not forget this!
}

The default mode for opening a file with ofstream's constructor is to create it if it does not exist, or delete everything in it if something does exist in it. If necessary, you can give a second argument that specifies how the file should be handled. They are listed below:

ios::app -- Opens the file, and allows additions at the end
ios::ate -- Opens the file, but allows additions anywhere
ios::trunc -- Deletes everything in the file
ios::nocreate -- Does not open if the file must be created
ios::noreplace -- Does not open if the file already exists

For example:
ofstream a_file("test.txt", ios::nocreate);

The above code will only open the file test.txt if that file already exists.


Lesson 11: Typecasting


Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single application.

To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.


For example:
#include <iostream.h>
int main()      
{
  cout<<(char)65;
  //The (char) is a typecast, telling the computer to interpret the 65 as a
  //character, not as a number.  It is going to give the ASCII output of
  //the equivalent of the number 65(It should be the letter A).
  return 0;
}


One use for typecasting for is when you want to use the ASCII characters. For example, what if you want to create your own chart of all 256 ASCII characters. To do this, you will need to use to typecast to allow you to print out the integer as its character equivalent.

#include <iostream.h>
int main()
{
  for(int x=0; x<256; x++)
  {  //The ASCII character set is from 0 to 255
    cout<<x<<". "<<(char)x<<" ";
  //Note the use of the int version of x to
        //output a number and the use of (char) to
  // typecast the x into a character  
        //which outputs the ASCII character that
  //corresponds to the current number
  }
  return 0;
}



Lesson 12: Introduction to Classes


C++ is a bunch of small additions to C, and one major addition. This one addition is the object-oriented approach. As its name suggests, this deals with objects. Of course, these are not real-life objects. Instead, these objects are the essential definitions of real world objects. Structures are one step away from these objects, they do not possess one element of them: functions. The definitions of these objects are called classes. The easiest way to think about a class is to imagine a structure that has functions.

What is this mysterious structure (not the programming type)? Well, it is not only a collection of variables under one heading, but it is a collection of functions under that same heading. If the structure is a house, then the functions will be the doors and the variables will be the items inside the house. They usually will be the only way to modify the variables in this structure, and they are usually the only to access the variables in this structure.
The idea to make programs more modular. A section of code will have its own functions and variables that control what it can do, and it does not require anything outside of itself to function. While the class may require initialization with data, it does not require outside variables or functions to manipulate the data. That allows programs to reuse the same code more easily.
From now on, we shall call these structures with functions classes (I guess Marx would not like C++). The syntax for these classes is simple. First, you put the keyword 'class' then the name of the class. Our example will use the name computer. Then you put an open bracket. Before putting down the different variables, it is necessary to put the degree of restriction on the variable. There are three levels of restriction. The first is public, the second protected, and the third private. For now, all you need to know is that the public restriction allows any part of the program, including that which is not part of the class, access the variables specified as public. The protected restriction prevents functions outside the class to access the variable. The syntax for that is merely the restriction keyword (public, private, protected) and then a colon. Finally, you put the different variables and functions (You usually will only put the function prototype[s]) you want to be part of the class. Then you put a closing bracket and semicolon. Keep in mind that you still must end the function prototype(s) with a semi-colon.

Classes should always contain two functions: the constructor and destructor. The syntax for them is simple, the class name denotes a constructor, a ~ before the class name is a destructor. The basic idea is to have the constructor initialize variables, and to have the destructor clean up after the class, which includes freeing any memory allocated. The only time the constructor is called is when the programmer declares an instance of the class, which will automatically call the constructor. The only time the destructor is called is when the instance of the class is no longer needed. When the program ends, or when its memory is deallocated (if you do not understand the deallocation part, do not worry). Keeps in mind this: NEITHER constructors NOR destructors RETURN AN ARGUMENT! This means you do not want to try to return a value in them.

The syntax for defining a function that is a member of a class outside of the actual class definition is to put the return type, then put the class name, two colons, and then the function name. This tells the compiler that the function is a member of that class.

For example:
void Aclass::aFunction()
{
  cout<<"Whatever code";
}


#include <iostream.h>
class Computer //Standard way of defining the class
{
public:
 //This means that all of the functions below this(and any variables)
 //are accessible to the rest of the program.
 //NOTE: That is a colon, NOT a semicolon...
Computer();
 //Constructor
~Computer();
 //Destructor
void setspeed(int p);
int readspeed();
  //These functions will be defined outside of the class
protected:
   //This means that all the variables under this, until a new type of
   //restriction is placed, will only be accessible to other functions in the
   //class.  NOTE: That is a colon, NOT a semicolon...
int processorspeed;
};  


Page : << Previous 6  Next >>