Home

Introduction to Values of a Program

   

Introduction to Variables

 

Introduction to Storage

 

A computer is an electronic device that is used to solve one specific problem or to perform a general assignment. For example, a fitness machine (Proform.com, 2010) allows a person to get in shape. A digital camera (Amazon.com, 2010) is used to take pictures. A cell phone (TigerDirect.com, 2010) is used to make phone calls. An ultrasound machine (Philips, 2010) is a health care machine used to produce images from inside a human body. A music synthesizer (Musician's Friend, 2010) can be used to create music:

Computer

Music Device

 

Cell Phone

Music Device

Music Device

An electronic device can also be used to solve general types of problems. For example, a personal computer (PC) can be used to perform calculations, word processing, or to store a database, etc.

In order to perform its assignment(s), a computer must receive values. This can be done by a person typing from a keyboard (cell phone, health care machine, PC, etc). Another machine would allow a user to only select from a preset number of keys (fitness machine, airplane, car, digital camera, microwave oven, refrigerator, etc). A person can also be asked to click something using the mouse. A person can also be asked to press some objects on a touch screen. In some cases, the values can come electronically (internally) from other sources (car, projector, etc). A computer can also get its values from a  combination of sources:

Information

To manage these different connections, a computer uses a flat object called a motherboard. Many parts are connected to this board. For example, there is a small machine whose primary job is to perform calculations; it is called a processor, and it is connected to the motherboard. Then external objects are connected to the parts connected to the motherboard:

Information

The values a computer receives must be stored somewhere, called memory (like human memory). The computer uses two categories of storage (memory): temporary and permanent. We will come back to permanent storage in a later lesson (not because it is difficult but because we don't need it for now). The computer's temporary memory is used to hold information for a while and then lose it if that information is not needed anymore. For example, it can hold some values while the computer is turned on. If the computer gets turned off, the values stored in the temporary memory are lost. This is not an anomaly: that's just the way it is designed (it would be catastrophic otherwise; try to imagine a computer that would keep everything put in its memory; it would be filled in a short time and blow up :)).

The memory area where the computer temporarily stores some values is called random access memory or RAM:

Random Access Memory

Let's illustrate memory as a small cake pan made of boxes or holes that can contain something:

Variable Representation

We must mention, and keep in mind, that memory is larger than that and is in fact made of millions of these hole-like objects.

As a programmer, your most regular job will consist of asking the compiler to temporarily store one or more values in the RAM. Without considering its small physical size, you should know that the RAM is huge, and you are not the only one using it. In fact, your program will not be the only one that uses the computer. For example, when the computer starts, it launches a program named an operating system (OS). Other programs (and utilities) also come to occupy the RAM.

To be able to manage the frequent requests of memory of your application, when you start a program, the compiler reserves a certain area of memory:

Reserved Memory

Because many programs use the RAM, if/when you want to store a value in it, you must provide some pieces of information. You must indicate the amount or memory you need and you must create a name that would be used to refer to that area of memory. The combination of these two pieces of information is called a variable.

ApplicationApplication: Introducing Variables

  1. Start Microsoft Visual C++ 2010 Express or Microsoft Visual Studio 2010
     
    Author Note From now on, we will only refer to Microsoft Visual C++
  2. To create a new application, on the Start Page, click New Project...
  3. If you are using Microsoft Visual Studio, in the left list, click Visual C++.
    In the middle list, click Win32 Console Application
  4. Set the Name to EmployeesRecords
  5. Click OK
  6. In the first page of the wizard, click Next
  7. In the second page, click Console Application and click Empty Project
  8. Click Finish
  9. To create a source to write code, on the main menu, click Project -> Add New Item...
  10. In the middle list, click C++ File (.cpp)
  11. Change the Name to Registration
  12. Click Add
  13. In the empty document, type the following:
    #include <iostream>
    using namespace std;
    
    void main()
    {
    }

Names

A variable must have a name and there are stricts rules you must follow to create a name. To start, there are words, called keywords, that you must not use because C and C++ use them. These keywords are:

asm auto bool break case catch char
char16_t char32_t class const const_cast continue decltype
default delete do double dynamic_cast else enum
explicit extern false finally float for friend
goto if inline int long mutable namespace
new nullptr operator private protected public register
reinterpret_cast return short signed sizeof static static_assert
static_cast struct switch template this throw true
try typedef typeid union unsigned using virtual
void   volatile   wchar_t   while

A context-sensitive keyword is a name that can be used, most of the time, as a normal name, but some other time is considered as a keyword. This means that the context-sensitive word can be used as a name but must be avoid in some cases. Most of the time, to be carefule, you should avoid using context-sensitive keywords as normal names because it can make your program difficult to read and sometimes can produce unpredictable results. The context-sensitive words in Microsoft C/C++ are:

abstract dllexport dllimport each export in
sealed          

As mentioned already, there are rules you must observe to name anything in your program. There are rules specified by the C and C++ languages but there are also rules you can add for your own taste. In our lessons, here are the rules we will follow to name things:

  • A name can consist of one letter (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, or z). Although these are letters of the US English alphabet, the C# language accepts international (non-US English) letters (that follow the Unicode standard)
  • The C# language allows that a name be made of an underscore only _. Although this is allowed, you should refrain from using the underscore as the only character of a name. It makes the code difficult to read
  • Except for the underscore, special symbols are not used anywhere in a name. Therefore, don't use |, !, ", /, $, %, ?, &, *, (, ), +, #, \, , @, , , , <, >, [, ], ;, {, }, or the comma inside any name
  • If the name is made of more than one character, it must start with either a letter or an underscore
  • After the first letter or underscore, the name can have a combination of letters, digits (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), and/or underscores
  • The name cannot have a space

Avoid starting a name with two underscores __. If you have to start a name with two underscores, avoid using the following words for names:

__alignof __asm __assume __based __cdecl
__declspec __event __except __fastcall __finally
__forceinline __identifier __if_not_exists __if_exists __inline
__int16 __m128 __m128d __m128i __int8
__int32 __int64 __m64 __interface __leave
__multiple_inheritance __noop __raise __single_inheritance __stdcall
__super __thiscall __try __unaligned __unhook
__uuidof __virtual_inheritance __w64 __wchar_t  

Besides these rules, you can add your own on top of the above restrictions. For example:

  • It the name of a variable is in one word, many people use lowercase letters
  • If the name is a combination of words, many people use the camel notation in which the first word is in lowercase and the first letter of each subsequent word is in uppercase

C and C++ are case-sensitive. This means that the names Case, case, and CASE are completely different.

Numeric Representations

 

Introduction

A computer program is a series of instructions that tell the computer what to do, when to do something, and how to do it. You, as the programmer, create these instructions. An example of an instruction would ask the program to store a number in the computer memory. Another instruction could ask the computer to add a number to the previously stored number. Another instructor could ask the computer to move something from one part to another. The instructions you write must be transmitted to the computer.

As you can imagine, different people write various and all types of instructions. To understand all of them and in fact to bring all these disparate instructions to one common language, the computer uses its own that all languages should understand and must follow. But they don't. Instead, a computer language submits its instructions to an intermediary program named an assembler. The assembler transforms the previous instructions into a shorter version that uses new words but that are still in English. Using this new version, the assembler transforms the instructions in an even more simplified version (in reality, there is nothing simple with this process) that the computer can understand.

The simplified language the computer understands uses a combination of 1s and 0s. This means that the assembler must bring your C/C++ instructions to 1s and 0s. The combinations or sequences of 1s and 0s indicate what needs to be done.

Numeric Systems

We are familiar with the system that uses 10 digits as 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. A combination of these 10 digits can produce any number we want. Because this system uses 10 digits. It is named the decimal system.

As mentioned already, the language of the computer is made of combinations of two values: 1 and 0. This is called the binary system (because it is based on two values only). Examples of numbers in the binary system, or binary numbers, are 1, 10, 1001, or 1010110111. When you submit a value to a computer, the value must be changed into a compbination of 1s and 0s.

You can imagine how hard it would be to represent a large number. One alternative uses the 10 digits of the decimal system and uses the first 6 letters of the English alphabet: A, B, C, E, D, and F or a, b, c, d, e, and f. This means that this system uses a combination of 16 characters to create any number. For this reason, it is called the hexadecimal system. To differenciate a hexadecimal number from a word, the number must start with 0x. Examples are 0x2, or 0xED8, or 0x962AAED3.

Signed and Unsigned

One of the characteristics of a number is to indicate whether it is lower than 0, equal to 0, or higher than 0. A number that is lower than 0 is said to be negative. Such a number must be preceded by -. If a number is higher than 0, it is said to be positive. Such a number can be preceded by + or no sign. The ability for a number to hold a sign makes it possible to say that such a number is signed. It is important to know that, when a number is said to be signed, that number can be negative or positive.

Any number that uses neither - or + is said to be positive and, because it doesn't use a sign, it is said to be unsigned. Normally, the 0 number doesn't use a sign.

Introduction to Data Types

 

Representing Memory Bits

We mentioned that, to store a value in the computer memory, you must indicate how much memory you will need and you must give it a name. The amount of memory you need is referred to as a data type. As you can imagine, different values require different amounts of memory. We also mentioned that the computer considers a value as a combination of 1s and 0s. The area of memory that holds a single piece of 1 or 0 is called a bit.

Consider a bit like a small object (like a cup of a cup cake) that can be full or can be empty:

Variable Representation

When it is empty, a bit holds a value or 0. When it is full, it holds a value of 1:

Variable Representation

Different combinations of empty (0) and full (1) objects produce the necessary values.

Declaring a Variable

To use a combination of bits, you let the compiler know that you want a variable. This is referred to as declaring a variable. As mentioned already, the amount of memory you need is called a data type. Therefore, when declaring a variable, you must specify the desired data type. In C and C++, a data type can be represented by one or more keywords.

To declare a variable, use the following formula:

DataType VariableName;

Redefining a Data Type

The data types we will use in our C/C++ applications are called built-in types because they are part of the language. As we will see, each data type uses either a word or a combination of words, which represents the name of the data type. The C language allows you to create a custom name; that is, a name of your choice from an existing data type. This is referred to as type-defining a data type.

To create a custom name for a data type, you use the typedef keyword. The formula to follow is:

typedef KnownDataType NewName;

The typedef keyword is required.

The KnownDataType represents a data type that is already defined either in C/C++, in Win32, in the MFC, or in your application. This means that the compiler must be able to locate that data type. If there is no such a data type or the compiler cannot find it, you will receive an error.

The NewName is the name you give to the data type. The name follows the rules we reviewed in the previous section. As you will find out in this lesson, the names of data types in the Win32 and the MFC libraries are in uppercase. This is not a rule, just a convention. This also means that you will easily differentiate a C data type and a Win32/MFC type by the case of the name: C/C++ data types are in lowercase, Win32/MFC types are in uppercase.

As mentioned already, to use a C data type, you don't have to include any particular library because they are built in the language. On the other hand, if you want to use a Win32 data type in your application, you must include the Windows.h header file.

Initializing a Variable

When you declare a variable by specifying its data type, you are asking the compiler to reserve a certain area and amount of memory to store the desired value. At that time, no value is actually stored in the reserved area of memory. It is filled with garbage. Initializing a variable consists of storing an initial value in that reserved area. The technique you use is the same for all types by the type of value you want to store depends: you should not and must not try to store just any type of value.

To initialize a variable, you have two options:

  • To initialize a variable when declaring it, specify its data type, followed by a name for the variable, followed by =, followed by the desired but appropriate value, ending with a semicolon. This can be done as follows:
    void main()
    {
        DataType VariableName = DesiredValue;
    }
  • To first declare a variable and later initialize it, first declare the variable by specifing its data type, its name, and ending with a semicolon. Then, on another line, type the name of the variable, followed by =, and the value. This can be done as follows:
    void main()
    {
        DataType VariableName;
    
        VariableName = DesiredValue;
    }

When you declare a variable and initialize it, the compiler stores its value in the memory that was reserved for it. You can then access that value when you want. And of course, you can change it if necessary.

C In

To support the ability to get values from a user, the C++ language provides an operator named cin (pronounced "see in") (which stands for Console Input). cin uses two greater than signs ">>" followed by the name of the variable in which the value will be stored.The formula to follow is:

cin >> VariableName;

If you are requesting many values from the user, you can write a statement that would act accordingly by separating values with as many >> operators as necessary. For example, to request a first name, last name, and an age on the same line, you could use:

cin >> firstName >> lastName >> Age;

A Combination of Four Bits

Although there are cases where you can use or access a bit, you cannot actually store a value in it. That is, you cannot ask the compiler to store the value 1 in a certain bit. This is because even the simplest value in C# needs more than one bit to store itself. Still, the minimum combination of bits you can be concerned with is four (in some languages, or in some implementations of the Assembly language, a combination of four bits is called a nibble).

By creating different combinations of empty (0) and full (1) objects grouped in four, you can get 16 combinations:

Combinations of Four Bits Combinations of Four Bits
Combinations of Four Bits Combinations of Four Bits

In a combination of four bits, the bits are counted as 0, 1, 2, and 3. The bit on the most right side is Bit 0 and it is called the low order bit (or LOBIT):

Four Bits

The last bit, the bit on the most left side, is Bit 3 and it is called the high order bit (or HIBIT).

If you represent the four-combination bits in binary formats, you get 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111, which produces 16 combinations. In decimal format, these combinations produce 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. In hexadecimal format, these combinations produce 0x0 (0x0000), 0x1 (or 0x0001), 0x2 (or 0x0002), 0x3 (or 0x0003), 0x4 (or 0x0004), 0x5 (0x0005), 0x6 (0x0006), 0x7 (or 0x0007), 0x8 (or 0x0008), 0x9 (or 0x0009), 0xA (or 0xa), 0xB (or 0xb), 0xC (or 0xc), 0xD (or 0xd), 0xE (or 0xe), and 0xF (or 0xF).

As a result, we get a table as follows:

Decimal Binary Hexadecimal
0 0000 0x0
1 0001 0x1
2 0010 0x2
3 0011 0x3
4 0100 0x4
5 0101 0x5
6 0110 0x6
7 0111 0x7
8 1000 0x8
9 1001 0x9
10 1010 0xA
11 1011 0xB
12 1100 0xC
13 1101 0xD
14 1110 0xE
15 1111 0xF

Table of Numeric Conversions

The minimum and maximum values in a combination of four bits are:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 15 0xf 1111
 

Introduction to Bytes

A byte is a combination of eight adjacent bits. The first bit, located on the most right side, is Bit 0. The last bit, on the most left side, is Bit 7:

Byte Representation

Bit 0 is called the least significant bit. It is also valled the low order bit or LOBIT. Bit 7 is called the most significant bit. It is also called the high order bit or HIBIT.

If you create different combinations of empty (0) and full (1) objects grouped in eight, in binary formats, you get 00000000, 00000001, 00000010, 00000011, 00000100, 00000101, 00000110, 00000111, 00001000, 00001001, 00001010, 00001011, 00001100, 00001101, 00001110, 00001111, etc, up to 11111111. When a large number is represented in binary format, it can be difficult to read. An alternative is to create groups of four bits so that instead of writing 01001011, you would write 0100 1011.

To evaluate the number of combinations in decimal formats, you use the number 2 that represents decimal, you elevate it to the power of the position of the bit (0, 1, 2, 3, 4, 5, 6, or 7), and you add the numbers. This can be done as follows:

27 + 26 + 25 + 24 + 23 + 22 + 21 + 20
= 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 255

Therefore, we get 255 possible combinations of eight bits. The combinations can also be represented in hexadecimal format as 0x1, 0x2, ..., 0xA, 0xA1, ..., 0xC8, ..., up to 0xFFFF

In the three numeric systems, we get:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 255 0xff 1111 1111

The minimum storage area offered by the (Intel) computer is the byte. As you know already, a byte is a group of 8 consecutive bits. The amount of memory space offered by a byte can be used to store just a single symbol, such as those you see on your keyboard. These symbols, also called characters, have been organized by the American Standard Code for Information Exchange (ASCII) in a set list. But, ASCII uses only 128 decimal numbers (based on a 7-bit format) to represent symbols counted from 0 to 127. To compensate for the remaining 1 bit, IBM used it to organize special characters, foreign language characters, mathematical symbols, small graphics, etc. Each one of these characters has a decimal, a hexadecimal, and a binary equivalents.

 
 
 

Characters

 

Introduction

Each one of the characters you see on your keyboard is represented as a numeric value, but whether it appears as a number, a letter, or a symbol, each one of these is considered a character. To display any character on your screen, you can use putchar() (which stands for pur-character). In the parentheses of putchar(), type the letter or symbol in single-quotess. Here is an example:

#include <iostream>
using namespace std;

void main()
{
    putchar('A');
}

This would produce the lette A. In reality, and as mentioned already, each character is represented by an ASCII numeric byte value. If you know that number, you can write between the parentheses of putchar(). Here is an example:

#include <iostream>
using namespace std;

void main()
{
    putchar(65);
}

In the English alphabet, a letter is one of the following symbols: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Besides these readable characters, the following symbols are called digits and they are used to represent numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. In addition, some symbols on the (US QWERTY) keyboard are also called characters or symbols. They are ` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > ".

To declare a variable for a letter or a symbol, you have many options. You can use the char keyword from the C language. To specify the value of the variable, type it in single-quotes. Here is an example:

#include <iostream>
using namespace std;

void main()
{
    char letter = 'a';
}

To display its value, write the name of the variable in the parenteses of putchar(). Here is an example:

#include <iostream>
using namespace std;

void main()
{
    char letter = 'a';

    putchar(letter);
}

To request a character from the user, you can use cin >> followed by the name of the variable that will hold the character. As an alternative, you can use _getch() and assign it to the variable of the character.

To provide its own representation of characters that can fit in 8 bits, the Win32 library has the CHAR data type. You can use it to declare a variable and initialize by including its character in single-quotes. Here is an example:

#include <iostream>
#include <Windows.h>
using namespace std;

void main()
{
	CHAR symbol = '$';

	putchar(symbol);
}

If the numeric value of a character is positive, such a character is referred to as unsigned. To declare a variable that can hold unsigned characters, use the unsigned char data type. Here is an example:

#include <iostream>
using namespace std;

void main()
{
	unsigned char letter = 'q';

	putchar(letter);
}

To support unsigned unsigned characters, the Win32 library provides the UCHAR data type. You can use it in the exact same you would use C's unsigned char.

Unicode and Wide Characters

At one time, the 7 bits set aside by ASCII were not enough to accommodate some characters and symbols, especially in non-Latin languages. The solution was to double the size, which was to use two bytes. This provided support for Unicode characters and symbols that are referred to as wide characters.

To declare a variable that can hold English and non-English characters, use the wchar_t keyword. To give a value to the variable, normally, you can just include it in single-quotes. Here is an example:

#include <iostream>
using namespace std;

void main()
{
	wchar_t symbol = '%';

	putchar(symbol);
}

A better alternative to indicate that you are dealing with a wide character is to precede its value with L. Here is an example:

#include <iostream>
using namespace std;

void main()
{
	wchar_t symbol = L'%';

	putchar(symbol);
}

To request a wide character from the user, you can use cin >> followed by the name of the variable. Alternatively, you can use _getwch() and assign it to the variable that must hold the character.

Besides wchar_t, you can declare a variable for a wide character using the char16_t keyword as data type. As the 16 number in its name indicates, this data type supports wide characters. You can use it the same way you would a wchar_t data type. Here is an example:

#include <iostream>
using namespace std;

void main()
{
	char16_t character = 'e';

	putchar(character);
}

To support Unicode, the Win32 library provides the TCHAR and the WCHAR data types. You can use them in the same way you would use wchar_t. Here is an example:

#include <iostream>
#include <Windows.h>
using namespace std;

void main()
{
	TCHAR symbol = L'&';

	putchar(symbol);
}

ApplicationApplication: Introducing Characters

  1. Change the file as follows:
    #include <iostream>
    using namespace std;
    
    void main()
    {
    	wchar_t gender;
    
    	printf_s("Enter Employees Gender (M for Male, F for Female, and U for Unknown: ");
    	gender = _getwch();
    }
  2. Save the file 

Escape Sequences

An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n.

An escape can be included in single-quotes as in '\n'. It can also be provided in double-quotes as "\n". The C language recognizes the following escape sequences:

Escape Sequence Name Description
\a Bell (alert) Makes a sound from the computer
\b Backspace Takes the cursor back
\t Horizontal Tab Takes the cursor to the next tab stop
\n New line Takes the cursor to the beginning of the next line
\v Vertical Tab Performs a vertical tab
\f Form feed  
\r Carriage return Causes a carriage return
\" Double Quote Displays a quotation mark (")
\' Apostrophe Displays an apostrophe (')
\? Question mark Displays a question mark
\\ Backslash Displays a backslash (\)
\0 Null Displays a null character
 

To use an escape sequence, you can also first declare a character variable and initialize it with the desired escape sequence in single-quotes.

ApplicationApplication: Using an Escape Sequence

  1. Change the file as follows:
    #include <iostream>
    using namespace std;
    
    void main()
    {
        wchar_t gender;
    
        printf_s("Enter Employees Gender (M for Male, F for Female, and U for Unknown");
        gender = _getwch();
    	
        _putwch('\n');
    
        printf_s("You typed ");
        _putwch(gender);
    	
        _putwch('\n');
        getchar();
    }
  2. To execute and test the application, on the main menu, click Debug -> Start Debugging
  3. When asked to enter a character, type F
    Enter Employees Gender (M for Male, F for Female, and U for Unknown
    You typed F
  4. Press Enter 

The Byte Data Type

As mentioned already, a byte is used to handle a storage area of 8 bits. By default, the storage is used to hold a small numeric value. To support it, the Win32 library provides the BYTE data type. When you declare a variable of type BYTE, you can specify its value using a single-quoted character or a (small) number. Here is an example:

#include <iostream>
#include <Windows.h>
using namespace std;

void main()
{
	BYTE byte = 65;

	putchar(byte);
}

When you initialize a BYTE variable using a number, if you use putchar() to display its value, the compiler would convert that number to its equivalent letter or symbol. To support wide characters and symbols, the Win32 library provides the TBYTE data type. You use it the same way you would use unsigned char. Here is an example:

#include 
#include 
using namespace std;

void main()
{
	TBYTE byte = 128;

	putchar(byte);
}

This would produce the character.

Because a byte primarily holds a numeric value, you can initialize it with a hexadecimal number. Here is an example:

#include <iostream>
#include <Windows.h>
using namespace std;

void main()
{
	TBYTE byte = 0xEE;

	putchar(byte);
}

This would produce the Euro symbol.

Introduction to Strings

 

A Group of Characters

A group of characters is called an array. This is a study we will cover when learning about arrays. For now, if you want to use a group of characters of any kind, you can declare a variable using either the char or the CHAR data type, followed by a valid name for the variable, followed by an opening square bracket [, followed by a number of characters, followed by a closing square bracket ], and ended with a semi-colon. The syntax to declare a group of characters is:

char VariableName[NumberOfCharacters];
CHAR VariableName[NumberOfCharacters];

The char keyword or the CHAR data type is required to let the compiler know that you want to create a variable that uses characters. The variable must have a valid name. The number of characters can be an estimate. For example, if you want to request employees' first names, type a number that you think would represent the largest name possible. The maximum number should be 80, but the average and a good regular number should be between 12 or 20. To represent an address or a similar long group of characters, use a dimension between 32 and 50. Here is an example:

char firstName[20];

To initialize an array of characters, do not specify the dimension and leave the square brackets empty. You can use the assignment operator and include the initialized value in double-quotes. Here is an example:

#include <iostream>
#include <Windows.h>
using namespace std;

void main()
{
    char university[] = "University of the District of Columbia";
    CHAR city[] = "San Pedro";
}

 As another technique, leave the square brackets empty, then add an opening and a closing parentheses. Inside the parentheses, enter the string in double-quotes. Here is a program:

#include <iostream>
using namespace std;

void main()
{
    char University[] = "University of the District of Columbia";
    char Faculty[]("Computer sciences");
}

To display the value of a string variable to the console using the C++ language, you can type it on the right side of cout <<. Here are examples:

#include <iostream>
using namespace std;

void main()
{
	char University[] = "University of the District of Columbia";
	char Faculty[]("Computer sciences");

	cout << "Welcome to the Student Orientation Program.\n";
	cout << "For your studies, we have selected:\n";
	cout << "Institution: ";
	cout << University;
	cout << "\n";
	cout << "Faculty: ";
	cout << Faculty;
	cout << "\n";
}

As an alternative using C, if you are using the char keyword or the CHAR data type, you can use printf_s().

To request an array of characters from the user, you have many options. In the C language, first declare the variable, then can use gets() or gets_s(). In the parentheses, enter the name of the variable. In C++, you can type the name of the array variable on the right side of cin >>. Here are examples:

#include <iostream>
using namespace std;

void main()
{
	char FirstName[12];
	char LastName[12];

	cout << "Enter First Name: ";
	cin >> FirstName;
	cout << "Enter Last Name: ";
	cin >> LastName;

	cout << "\nFull Name: " << FirstName << " " << LastName;
	cout << endl;
}

Alternatively, you can use the following formulas:

cin.getline(VariableName, Dimension);
cin.getline(VariableName, Dimension, Delimeter);

To use the array variables, change the content of the file as follows:

#include <iostream>
using namespace std; 

void main()
{
    	char FirstName [20], LastName [20];
    	char Address [40];
    	char JobPerformed [80];

	cout << "Welcome to College Park Auto-Parts\n";
    	cout << "Enter the following information about the customer's.\n";
    	cout << "First Name: ";
    	cin >> ws;
    	cin.getline(FirstName, 20);
    	cout << "Last Name: ";
    	cin >> ws;
    	cin.getline(LastName, 20);
    	cout << "Address: ";
    	cin >> ws;
    	cin.getline(Address, 40);

    	cout << "Describe the job performed on the customer's car in 100 words or less:\n";
    	cin >> ws;
    	cin.getline(JobPerformed, 80);

    	cout << "\nCPAP Invoice # 1202";
    	cout << "\nCustomer Name: " << FirstName << " " << LastName;
    	cout << "\nAddress: " << Address;
    	cout << "\nJob Performed: " << JobPerformed;
    	cout << "\n\n";
}

Wide Strings

A regular string uses characters and symbols that need 8 bits each. In Unicode, a string may use international characters outside of the English language. To declare a string variable as an array of characters and that can hold all types of symbols, you can use the wchar_t data type:

wchar_t VariableName[NumberOfCharacters];

As you can see, the formula is the same as done for the char data type. To specify the value of the variable, you have many options. If you want to initialize the variable when declaring it, leave the parentheses empty and assign a string to it. This time, the string can start with L. Here is an example:

#include <iostream>
using namespace std;

void main()
{
    wchar_t city[] = L"Rio de Janeiro";
}

As another solution, if you are using Win32 in your code, precede the string with TEXT and include the string in parentheses. Here are examples:

#include <iostream>
#include <Windows.h>
using namespace std;

void main()
{
    wchar_t city[] = L"Rio de Janeiro";
    wchar_t country[] = TEXT("Emirats Arabes Unis");
    wchar_t team[](TEXT("Football Club Internazionale Milano"));
}

In an MFC application, you can start the string with _T the same way you would use TEXT. Here is an example:

#include <iostream>
#include <AfxWin.h>
using namespace std;

void main()
{
    wchar_t city[] = L"Rio de Janeiro";
    wchar_t country[] = TEXT("Emirats Arabes Unis");
    wchar_t team[](TEXT("Football Club Internazionale Milano"));
    wchar_t player[] = _T("Samuel Eto'o Fils");
}

To display the value of a variable that holds a wide string, you can use _putws(), wprintf, or wprintf_s(). In all cases, type the name of the variable in the parentheses. Here are examples:

#include <iostream>
#include <AfxWin.h>
using namespace std;

void main()
{
    wchar_t city[] = L"Rio de Janeiro";
    wchar_t country[] = TEXT("Emirats Arabes Unis");
    wchar_t team[](TEXT("Football Club Internazionale Milano"));
    wchar_t player[] = _T("Samuel Eto'o Fils");

    _putws(city);
    _putws(country);
    wprintf(team);
    wprintf_s(L"\n");
    wprintf_s(player);
    wprintf_s(L"\n");
}

To request the value of a variable that can hold a wide string, based on the C language, use _getws_s() or _getws(). In the parentheses, enter the name of the variable.

Practical LearningPractical Learning: Using Strings

  1. To use string variables, change the document as follows:
    #include <iostream>
    using namespace std;
    
    void main()
    {
    	wchar_t gender;
    	wchar_t firstName[20];
    	wchar_t lastName[20];
    
    	wprintf_s(L"Enter Information About the Employee");
    	_putwch('\n');
    	wprintf_s(L"First name: ");
    	_getws(firstName);
    	wprintf_s(L"Last name: ");
    	_getws(lastName);
    
    	wprintf_s(L"\n");
    	wprintf_s(L"=//= Employee Record =//=\n");
    	wprintf_s(L"Full Name: ");
    	wprintf_s(firstName);
    	wprintf_s(L" ");
    	wprintf_s(lastName);
    	wprintf_s(L"\n");
    
        	getchar();
    }
  2. To execute the application, on the main menu, click Debug -> Start Debugging.
  3. Enter the first name as Raymond and press Enter
  4. Enter the last name as Watts and press Enter:
    Enter Information About the Employee
    First name: Raymond
    Last name: Watts
    
    =//= Employee Record =//=
    Full Name: Raymond Watts
    
  5. Press Enter to close the DOS window and return to your programming environment

Strings

A string is a character, a group of characters, or an empty space that you want the compiler to treat "as is". Besides using an array of characters, a special library called the Standard Template Library (STL) provides an alternative. You can declare a string using the string word (it is a class).

To use a string in your program, first include the string library using the using namespace std; expression. In your program, declare a variable starting with the word string followed by a valid name for the variable. Here are examples:

string Continent;
string Company;

When requesting its value from the user, by default, string is used to get only a one-word value. Here is an example program that requests a first and last names:

#include <iostream>
#include <string>
using namespace std;

void main()
{
	string FirstName, LastName;	

	cout << "Enter first name: ";
	cin >> FirstName;
	cout << "Enter last name: ";
	cin >> LastName;

	cout << "\n\nFull Name: " << FirstName << " " << LastName << "\n\n";
}

You can initialize a string variable of any length. One technique is to use the assignment operator and include the string in double-quotes. Here is an example:

string UN = "United Nations";
cout << "The " << UN << " is an organization headed by a Secretary General";

Another technique involves using parentheses following the name of the string variable, and including the string in double-quotes. Here is an example:

string BookTitle("Drugs, Sociology, and Human Behavior.");

cout << "For our class next week, please read \"" << BookTitle;cout << "\"";

If you want to request the value of the variable from the user, you should use the getline function. To use the getline function, follow this formula:

getline(cin, StringName);

Inside of the parentheses, the word cin informs the compiler that the request will come from an external source, mainly the user typing from the keyboard. The StringName is the name you declared the variable with. The getline() function expects that the user will press Enter to end the sentence; the end line character is "\n".

Here is an example program that requests strings of any length from the user:

#include <iostream>
#include <string>
using namespace std;

void main()
{
	string MusicAlbum;
	string TrackTitle;

	cout << "Welcome to Radio Request where the listeners select their songs:\n";
	cout << "Type the album name: ";
	getline(cin, MusicAlbum);
	cout << "Type the song title: ";
	getline(cin, TrackTitle);

	cout << "\nNow for your pleasure, we will play: " << TrackTitle
	     << "\nfrom the " << MusicAlbum << " wonderful album.\n\n";
}

If you want the user to end the sentence with another character such as * or !, use the following function

getline(cin, StringName, Delimiter);

The following example uses the = symbol as the end character of the sentence:

string Address;
cout << "Enter your address. To end, type = ";
getline(cin, Address, '=');
cout << "\nSo, you live at: " << Address;

Here is an example:

#include <iostream>
#include <string>
using namespace std;

void main()
{
	string FirstName, LastName;	

	cout << "Welcome to College Park Auto-Parts\n"; 
	cout << "Enter the following information about the customer's.\n";
	cout << "First Name: "; 

	cin >> FirstName;
	cout << "Last Name: ";
	cin >> LastName;

	cout << "\n\nCPAP Invoice # 1202";
	cout << "\nCustomer Name: " << FirstName << " " << LastName << "\n\n";
}

When requesting a string made of various words, such as an address, you can use the getline() function as follows:

#include <iostream>
#include <string>
using namespace std;

void main()
{
	string FirstName, LastName;
	string Address;
	string JobPerformed;

	cout << "Welcome to College Park Auto-Parts\n";
	cout << "Enter the following information about the customer's.\n";
	cout << "First Name: ";
	cin >> FirstName;
	cout << "Last Name: ";
	cin >> LastName;
	cout << "Address: ";
	getline(cin, Address);
	cout << "Describe the job performed on the customer's car:\n";
	getline(cin, JobPerformed);

	cout << "\n\nCPAP Invoice # 1202";
	cout << "\nCustomer Name: " << FirstName << " " << LastName;
	cout << "\nAddress: " << Address;
	cout << "\nJob Performed: " << JobPerformed << "\n\n";
} 
 
 
   
 

Previous Copyright © 2010 FunctionX, Inc. Next