473,513 Members | 2,446 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ


C++ Variables and File Handling

By John Bourbonniere
Developer, PlayZion.com

Basic Variable Types:

Note: You can use the keyword 'unsigned' before any of the above to restrict the class to hold only positive integer values.

Math Operators

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.

 

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.