C++ Variables and File Handling
Developer, PlayZion.com
Basic Variable Types:
- Integral Classes
- char (single characters, such as '
T', 'x', or '9'. Use single quotes) - short (short integers)
- int (medium-sized integers)
- long int (long integers)
Note: You can use the keyword 'unsigned' before any of the above to restrict the class to hold only positive integer values.
- Floating point classes
- float (real numbers that allow scientific notation)
- double (real numbers with greater precision than 'float')
- long double (real numbers with greater precision than 'double')
- Strings Such as "Hello world". In order to use strings, you must type
#include "cstring.h"at the beginning of your program
Math Operators
- addition:
+ - subtraction:
- - multiplication:
* - division:
/ - modules:
% - assignment:
=
Order of operations: Expressions in brackets are evaluated first. The operators *, /, and % are evaluated from left to right in the order they appear. After that, + and - are evaluated from left to right.
Declaring Variables:
<class> <variable name>;
Or, to assign a value to assign a value to the variable right away, you can type
<class> <variable name> = <initial value>;
For example,
int ab = 5;
unsigned long int cd = 3948293;
float answer;
Input and Output
If you want to write a value to the screen, just type
cout << <value>;
To start a new line, type cout << endl;
You can combine these two, along with variables.
For example,
cout << "You are " << age << " years old." << endl;
To read a variable in, type cin >> <variable>;
To use input and output in your programs, you must type
#include <iostream.h>
at the beginning of your programs.
Input and output with files
Do use input and output with files, you must type
#include <iostream.h>
at the beginning of your programs.
You must first declare a variable to open a file.
To do this, type ofstream MyFile; (or any value you want for 'MyFile'). Then, you can perform operations with it.
For example,
MyFile.Open ("c:\testfile.txt");
After that, you can output to the file just as you would output to the screen, except you type the value of the file first.
For example,
MyFile << "Line one of output" << endl;
When you're finished writing to the file, you must close it. To do this, type MyFile.close();
Reading from a file is just as easy. You must declare an input file as 'ifstream'.
For example,
ifstream MyFile ("textfile.txt");
MyFile >> a;
MyFile >> b;
cout << "the file contained the values " << a << " and " <<
b << endl;
MyFile.close()
You can read and write to the same file, but make sure you don't do it at the same time. You must close between operations.
