Previous Page TOC Next Page



- 6 -
String Data and I/O


string literals


What You'll Learn


Visual C++ differs from many other programming languages in that there is no such thing as a character string variable. There are character variables, but they hold only a single character of data. There are character string literals, but no character string variables. A string is simply a list of characters such as a word, phrase, sentence, or any set of characters strung together. If you have never programmed before, you will not miss string variables. If you have programmed in other languages, you might question Visual C++'s usefulness because it does not support string variables.

The designers of the C++ language decided against using string variables, but C++ offers alternatives to them that are almost as easy to use and much more efficient. After all, Visual C++ must offer a way for you to store people's names and addresses. This unit shows you how to designate string literals and how to store them in memory.

Performing input and output (often referred to as just I/O) is extremely easy with Visual C++. You need a way to get data and results of calculations to the screen and to get input from the user at the keyboard. This book has already used cout and cin for simple input and output.

After you learn about storing character and string data, you will have mastered all the fundamental data types in Visual C++. You will then need some way to output that data. This unit reviews cout and cin, and then explains how to make them work exactly the way you want.



Lesson 2's second unit gave a brief overview of character and string data as well as Visual C++'s I/O capabilities. This unit explains all the details that were skipped then. This unit also begins showing you full-length programs again now that you'll finally understand what all the statements do.


Character Literals and Variables




Character literals always appear inside single quotation marks. Define char variables for character data.

All character literals must appear between two single quotation marks. All of the following are character literals:


'A'     'x'     ' '     '*'     '&'     '1'

As you can see, a character is any character—whether a letter, number, space, or special character—enclosed in single quotes. Never put single quotation marks around something other than a single character of data.



Remember that C++ is extremely fussy about the characters you type to give it instructions. ' and " have two very different meanings and cannot be used interchangeably.

In the previous unit, you learned how to define a character variable with the char keyword. The following statement defines a character variable:


char MyGrade;   // Defines a character variable

Your program can store a character inside MyGrade using the assignment operator, =. The following assignment statement stores an A in MyGrade:


MyGrade = 'A';    // Store character data in the character variable

Later in the program, another assignment might store a different value in MyGrade, either by assigning another character literal to the variable or by assigning another variable to MyGrade, such as this:


MyGrade = oldGrade;   // Replace the contents of MyGrade


If you know a character variable's initial value at the time that you define the variable, you can assign the variable a value at the same time you define the variable, like this:


char MyGrade = 'A';  // Define and initialize

Listing 6.1 contains the beginnings of a Visual C++ program that defines and initializes three character variables.



Define character variables with char and specify character literals by enclosing them inside single quotation marks.

Input Listing 6.1. Defining and storing values in three character variables.

1:  void main()

2:  {

3:    char first, middle, last;

4:    first = 'G';

5:    middle = 'M';

6:    last = 'P';

7:    // Rest of program would follow

Output

There is no output from Listing 6.1 because the program is not complete.

Analysis

definition

A delimiter is a character used to signal or enclose data.

The code declares three variables, and then assigns three initials to them. The initials are character literals because they are enclosed in single quotation marks. Visual C++ does not store the quotation marks in the three variables, only the characters. The single quotation marks serve only to delimit the character literals.

What if the character literals in this partial program did not have single quotation marks? What would Visual C++ do with the G, M, and P? Visual C++ would think that G, M, and P were three variables! Because it would not have seen any definition for those variables, Visual C++ would issue an error message. The quotation marks are vital to let Visual C++ know that you are assigning character literals and not other variables.

String Literals




Enclose string literals inside quotation marks. All string literals end with a special string-terminating zero. Even though you cannot see this string-terminating zero, Visual C++ uses the string-terminating zero to detect the end of all strings.

One type of Visual C++ literal, called the string literal, does not have a matching variable to hold it. A string literal is always enclosed in double quotation marks (which are often called just quotation marks). The following are examples of string literals:


"C++ Programming"   "123"   " "   "4323 E. Oak Road"   "x"

Any string of characters between double quotation marks—even a single character—is considered to be a string literal. A single space, a word, or a group of words between double quotation marks are all C++ string literals.

If the string literal contains only numeric digits, it is still not a number; it is a string of numeric digits that cannot be used to perform mathematical calculations. You can perform calculations on numeric data only, not on string literals.

A string literal is any character, digit, or group of characters enclosed in double quotation marks. A character literal is any character enclosed in single quotation marks. That is how you determine whether a literal is a character or a string. If the literal has no quotation marks, it is a numeric constant.

The quotation marks are never considered part of the string. The quotation marks surround the string and simply inform the Visual C++ compiler that the code is a string literal and not another type of literal.

It is easy to print string literals. Simply put the string literals in a cout statement. The following code prints a string literal to the screen:


cout << "Visual C++ Programming in 12 Easy Lessons";

You can just as easily print character literals like this:


cout << 'A'  << 'B'  << 'C';

Later in this unit, you'll read more details on using cout, but as you can see, printing string and character data with cout is extremely easy.

String-Literal Endings


One additional aspect of string literals sometimes confuses beginning C++ programmers. All string literals end with a special string-terminating zero. You do not see the string-terminating zero, but C++ stores it at the end of the string in memory. Figure 6.1 shows what the string "C++ Lesson" looks like in memory.

Figure 6.1. In memory, a string literal always ends with 0.

You do not have to worry about putting the string-terminating zero at the end of a string literal. Visual C++ does it for you every time it stores a string. If your program contained the string "C++ Lesson", for example, the compiler would recognize it as a string literal (from the double quotation marks) and store the string-terminating zero at the end.

The string-terminating zero is important to C++. It is rarely called just a zero because zero is normally reserved for the number 0. Visual C++ uses the string terminator to know where the string literal ends in memory. (Remember that the double quotation marks are not stored as part of the string, so Visual C++ cannot use the quotation marks to determine where strings end.)

definition

The first entry in the ASCII table is called the null zero.

Not only is the string-terminator different from the number zero, but the string-terminator is not the same as the character zero either. If you look in Appendix B's ASCII Table, you see that the first entry is the null-zero character. The null-zero character, ASCII value 0, is what strings end with. This string-delimiting zero is different from the character '0', which has an ASCII value of 48.



The string-terminator is called by all of the following names: ASCII 0, null 0, string-terminating 0, binary 0, and even '\0'. That last one is strange due to the backslash. Figure 6.1 used this '\0' to end its string. The backslash in a character value means that the following literal character will be treated in a special way, which will be shown later in the section "Special Characters: Escape Sequences."

definition

A bit is an on or off switch inside your computer represented by 1s and 0s.

Computers do not really store characters. They store bit patterns of 1s and 0s and each combination of those patterns represents individual characters. These 1s and 0s are called binary numbers. If you've never learned about binary before, you might want to review Assembly Language: For Real Programmers Only from Sams Publishing. All memory locations in your computer actually hold bit patterns of characters. If the letter A is stored in memory, an A is not actually there; the binary bit pattern for the ASCII A (01000001) is stored there. Because the binary bit pattern for the null zero is 00000000, the string-delimiting zero is sometimes called a binary zero.

To illustrate these bit patterns further, Figure 6.2 shows the bit patterns for the following string literal when stored in memory:


"I am 30"

Figure 6.2 shows how a string is stored in your computer's memory at the bit level. It is important for you to recognize that the character 0 inside the number 30 is not the same 0 (at the bit level) as the string-terminator. If it were, Visual C++ would think that this string ended after the 3, which is incorrect.

Figure 6.2. The bit pattern showing that a string terminator and a character zero are different.

String Lengths


Your program often has to know the length of a string. This becomes critical when you learn how to accept string input from the keyboard. The length of a string is the number of characters up to, but not including, the string terminator. Do not include the string terminator in the count, even though you know that C++ adds it to the end of the string.

Table 6.1 shows some string literals and their corresponding string lengths.

Table 6.1. String literals and their lengths.

String Length
"X" 1
"0" 1
"Sam" 3
"" 0
"The Computer" 12

All character literals have a length of one, with no exception. There is no string terminator for character literals. The double quotation marks signal to Visual C++ that a string terminator is needed, so C++ adds one to the end of every string inside double quotes.

You should know that the following are different to Visual C++:


'R' and "R"

'R' is not a string. It could be a string only if it were enclosed within regular (not single) quotation marks. 'R' is a single character literal. 'R' does not have a terminating zero because it is not a string literal. 'R' is one character long, because all character literals (and variables) are one character long. "R" is a string literal because it is delimited by double quotation marks. Its length is also one, but it includes a terminator in memory so that Visual C++ knows where the string ends. Due to this difference, you cannot mix character literals and character strings. Figure 6.3 shows how 'R' and "R" are stored in memory.

Figure 6.3. 'R' is a character literal and "R" is a string literal.

Listing 6.2 contains a simple program that prints a string literal.



All strings end with terminators inside memory. The terminator tells Visual C++ where the string ends. The length of a string is the number of characters up to, but not including, the terminator.

Input Listing 6.2. Printing a string literal.

1:  // Filename: STLITPR.CPP

2:  // Printing string literals is easy

3:  #include <iostream.h>

4:

5:  void main()

6:  {

7:     cout << "This is a string literal.";

8:     return;

9:  }

Output


This is a string literal.

Analysis

Line 7 prints a string on the screen using cout and the << operator. The string printed happens to be 25 characters long, but in memory, the string consumes 26 bytes due to the terminator at the end of the string.

Line 8's return sends control back to Visual C++'s QuickWin environment.

Special Characters: Escape Sequences




There are several escape sequences that control output.

All the alphabetic, numeric, and special characters on your keyboard can be character literals. Some characters, however, cannot be represented by using your keyboard. They include some of the higher ASCII characters (such as the Spanish Ñ). Because you do not have keys for every character in the ASCII table, C++ enables you to represent these characters by typing their ASCII hexadecimal number inside single quotation marks.

You can still use all the ASCII characters, even if they are not on your computer's keyboard. To store the Spanish Ñ in a variable, look up its hexadecimal ASCII number in Appendix B. You find that it is A5. Add the prefix \x to it and enclose it in single quotation marks:


char sn='\xA5';   // Puts the Spanish Ñ into

                  // a variable called sn

Looking at the '\xA5', you might wonder how a single character can reside between those quotes. Earlier it was stated that single quotes always enclose a single character. Even though '\xA5' contains four characters inside the quotation marks, those four characters represent a single character, not a character string. If you were to include those four characters inside a string literal, C++ would treat \xA5 as a single character in the string. The string literal


"An accented a is \xA0"

is a C++ string that is 18 characters, not 21 characters. C++ interprets the \xA0 character as the [as]a, just as it should. The backslash (\) signals to C++ that it should treat the next characters in a special way, not as a three-character string.

In addition to the hexadecimal ASCII codes you just read about, Visual C++ defines several escape sequences shown in Table 6.2.

definition

An escape sequence represents special control characters.

Table 6.2. Visual C++'s special escape sequence characters.

Escape Sequence Meaning
\a Alarm (a beep from the speaker)
\b Backspace
\f Form feed (new page on printer)
\n Newline (carriage return and line feed)
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash (\)
\? Question mark
\' Single quotation mark
\" Double quotation mark
\000 Octal number
\xhh Hexadecimal number
\0 Terminator (or binary zero)


From the table, you might realize that the way to create a string with quotes in it is to use an escape character, as in this example:


"\"This string is in quotes\""


Integers and Characters




Characters and integers are often interchangeable.

Visual C++ associates characters very closely with their ASCII numbers. Therefore, you can perform arithmetic on character data. This is one of the few places where it is okay to mix data types. Visual C++ integers and characters work well together thanks to the ASCII table in Appendix B. The section of code


char c;

c = 'A' + 7;   // Adds 7 to the ASCII character

actually stores an H in the character variable c. The ASCII value of the letter A is 65. Adding 7 to 65 produces 72. Because the variable c is not an integer variable but a character variable, Visual C++ uses the ASCII character value for H, not a 72, as the resulting value of c.

You also can store character literals in integer variables. If you do, Visual C++ stores the matching ASCII number for that character. The section of code


int i = 'A';

does not put a letter A in i because i is not a character variable. Visual C++ assigns the number 65 in the variable because 65 is the ASCII number for the letter A.

Integers and characters are about the only data types that Visual C++ safely mixes without a problem. You'll learn in Lesson 5, "Upgraded Operators," how to mix other data types safely.

Fortunately, you rarely need to use escape sequences unless you are writing a technical program or wanting to write strings with quote marks in them. One common pitfall is trying to write a DOS filename in a string, and then wondering why a program cannot find the file. What file does the following represent?


cout << "C:\temp\newfile.txt";

To correctly write a DOS filename, you need to use the double backslash escape sequence:


cout << "C:\\temp\\newfile.txt";

Listing 6.3 contains a program that defines three integer variables and three character variables but stores the opposite data type in each.



You can store integers in character variables and characters in integer variables. In Lesson 6, "Looping Back and Forth," you'll learn how to set up repeating code that produces a series of characters while incrementing integers.

Input Listing 6.3. Mixing integers and characters.

1:  // Filename: INTCHAR.CPP

2:  // Mixing integers and characters

3:  #include <iostream.h>

4:  void main()

5:  {

6:    int i, j, k;   // Define 3 integers

7:    char c, d, e;  // Define 3 characters

8:

9:    // Mix the data

10:   i = 'A';   // Stores 65 in i

11:   j = 'B';   // Stores 66 in j

12:    k = 'C';   // Stores 67 in k

13:

14:    c = 88;    // Stores 'X' in c

15:    d = 89;    // Stores 'Y' in d

16:    e = 90;    // Stores 'Z' in e

17:

18:    cout << i << ", " << j << ", " << k << '\n';

19:    cout << c << ", " << d << ", " << e << '\n';

20:    return;

21:  }

Output


65, 66, 67

X, Y, Z

Analysis

Even though lines 10 through 12 store the characters A, B, and C in variables, the numbers 65, 66, and 67 appear in the output because the variables are integer variables. Also, even though lines 14 through 16 store 88, 89, and 90, the output is X, Y, and Z due to the fact that the variables are character variables. The ASCII table's mapping of characters to integer values produces these results.

Storing Strings in Arrays




There are no string variables, but you can store strings in character arrays.

Although Visual C++ has no string variables, character arrays work well for holding strings. The concept of an array might be new to you. As you will see in the rest of this unit, arrays are not difficult to understand. There are several kinds of arrays—integer arrays, floating-point arrays, and so on. As soon as you have mastered character arrays, the remaining array types (discussed in Lesson 8, "Lots of Data,") will be easy for you.

An array is a list (sometimes called a table) of variables. Most programming languages allow the use of such lists. Suppose that you have to keep track of the sales records of 100 salespeople. You could make up 100 variable names and assign a different salesperson's sales record to each one.

All those different variable names, however, are difficult to track. If you were to put the sales records in an array of floating-point variables, you would have to keep track of only a single name (the array name) and reference each of the 100 values by an index, normally called a subscript.

Later lessons in this book cover array processing in more detail. Because a string is simply a list of one or more characters, a character array is the perfect place to hold strings of information. Suppose that you want to keep track of a person's full name in a variable. There is no way, given what you have learned so far about variables, to store a string of characters in a single variable. Visual C++ supports an array of characters in which you can store multiple characters. A character array holds one or more character variables in a row in memory. This line defines such an array:


char fullName[10];   // fullName can hold a string

definition

A character array is the C++ aggregate variable that holds multiple characters.

fullName is a character array. Always include brackets ([]) after an array name that you declare. This array is 10 characters long, and its name is fullName. You also can assign a value to the character array at the time you define the array. The following definition statement not only defines the character array, but also assigns the name "Ted Jones" at the same time:


char fullName[10] = "Ted Jones";

All characters in an array are stored contiguously in memory. Figure 6.4 shows what fullName looks like in memory. Each of the 10 boxes of the array is called an element. Notice the terminator (the string-terminating character) at the end of the string. Notice also that the last character of the array contains no data. You filled only the first nine elements of the array with the data and the data's terminator. The tenth element does have a value in it, but whatever follows the string's terminator is not a concern.

Definition

Contiguous means that each item is next to each other with no space in between.

Figure 6.4. Defining a character array that holds a string.

The parts of an array are available, as is the array as a whole. This is the primary advantage of using an array rather than using many differently named variables. You can assign values to the individual array elements by putting the elements' location (called a subscript) in brackets, as follows:


name[1] = 'a';

This overwrites the e in the name Ted with an a. The character array now holds "Tad Jones".

All C++ array subscripts start at zero. Therefore, to overwrite the first element, you must use 0 as the subscript. Assigning name[1] (as done earlier) changes the value of the second element in the array, not the first.

You can print individual elements of an array as well. The statement


cout << name[0] << ". " << name[4] << ".";

prints this:


T. J.

You can print the entire string—or, more accurately, the entire array—with a single cout statement, as follows:


cout << name;

Notice that when you print an array, you do not include brackets after the array name. You must be sure to reserve enough characters in the array to hold the entire string. The line


char name[5]="Ted Jones";

is incorrect because it reserves only five characters for the array, whereas the name and its terminator require 10 characters. Visual C++ issues the error message array bounds overflow if you do not reserve enough characters.



Always reserve enough array elements to hold the string and its null-terminating character. It is easy to forget the extra place for the null character, but don't!

If your string contains 12 characters, it also must have a thirteenth location for the terminator or it will never be treated like a string. To help eliminate this error, C++ gives you a shortcut. The following two character array statements are the same:


char horse[13] = "Conservative";

and


char horse[] = "Conservative";

You can specify empty brackets only when you assign a value to the character array at the same time you declare the array. C++ counts the string's length, adds one for the terminator, and reserves the array space for you. If you do not assign a value to an array at the time it is declared, you cannot declare it with empty brackets. The statement


char initials[];   // Do not do this!

does not reserve any space for the array called initials. Because you did not assign a value to the array when you declared it, C++ assumes that this array contains zero elements. Therefore, you have no room to put values in this array later. Visual C++ generates an error if you attempt this.

An array is not a single variable but a list of variables. A character variable holds a single character, and a character array holds a bunch of character variables. Instead of that bunch of variables having different names, they all have the same name (the name of the array).

Arrays Versus Strings


Strings can exist in Visual C++ only as string literals, or as data residing in character arrays. Strings must be stored in character arrays, but not all character arrays contain strings.

Look at the two arrays shown in Figure 6.5. The first one, called first, is a character array, but it does not contain a string. Rather than a string, it contains a list of several characters. The second array, called second, contains a string because it has a terminator at its end.

Figure 6.5. first contains characters, and second contains a character string terminated by a terminator.

There are two ways to initialize these arrays. Here is an example of filling them with assignment statements at the point where they are defined:


char first[10]={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',

'i', 'j'};

char second[10]="Excellent";

You must enclose the list of characters in braces as shown in Figure 6.5 if you want to put only individual characters in an array. You could initialize first later in the program, using assignment statements as the following code section does.


char first[10];

first[0]='a';

first[1]='b';

first[2]='c';

first[3]='d';

first[4]='e';

first[5]='f';

first[6]='g';

first[7]='h';

first[8]='i';

first[9]='j';   // 9 is the highest subscript

Because first does not contain a terminator, it does not contain a string of characters. It does contain characters that can be stored in the array (and used individually), but they can't be treated in a program as if they were a string.



Never try to assign string values to character arrays using a regular assignment statement, except when you first define the character arrays.

Character arrays are not string variables (arrays can be used only to hold a string of characters), and they cannot go on the left side of an equal (=) sign. This program issues an error:


// Filename: ARAEQUAL.CPP

#include <iostream.h>

void main()

  {

    char dogName[20];   //  Reserves space for the dog's name

    dogName = "Ross";   // INVALID!

    cout << dogName;    // The program will never get here

    return;

  }

Because the dog's name was not assigned at the time the character array was declared, it cannot be assigned a value later. The following assignments are allowed if you replace the previous program's assignment with them:


dogName[0]='R';   // Assigns values one element at a time

dogName[1]='o';

dogName[2]='s';

dogName[3]='s';

dogName[4]='\0';  // Needed to ensure that this is a string!}

The dogName character array now holds a string because the last character is a terminator.

The length of the string is always the number of characters in the character array up to, but not including, the string-terminating null. The number of elements reserved for an array can be (and usually is) different from the string length. The character array in the preceding code contains 20 elements. This remains true whether those elements contain a string or just some character data.

You can't assign more than 20 characters to dogName because its reserved space is only 20 characters. However, you can store any string of 19 (leaving one for the terminator) or fewer characters to the array. If you assign the "Ross" string in the array as shown, and then assign a terminator to dogName[3] as in


dogName[3] = '\0';

the string in dogName is now only three characters long. You have, in effect, shortened the string. There are still 20 characters reserved for dogName, but the data inside it is the string "Ros" ending with a terminator.

Visual C++ does give you ways to assign values to strings. You can use the strcpy() function, for example. This is a built-in function that enables you to copy a string literal in a string. To copy the "Benji" pet name into the dogName array, type the following:


strcpy(dogName, "Benji");   // Copies Benji into the array

The strcpy() (string copy) function assumes that the first value in the parentheses is a character array name and that the second value is a valid string literal or another character array that holds a string. You must be sure that the first character array in the parentheses is long enough (in number of reserved elements) to hold whatever string you copy into it.



All programs that use strcpy() must have the following line inserted at the top of the program with the other #define preprocessor directives:


#include <string.h>

Visual C++ supplies the STRING.H file to help the strcpy() function work properly. The #include files such as IOSTREAM.H and STRING.H are explained in more detail in later lessons.

It is worth explaining how C++ uses the terminator character. C++ does not keep track of the length of a string, so functions such as strcpy simply look along the character array until they find a terminator. They cannot tell the length of the character array (C++ does not store that information internally either), so they keep looking until they find one, even if this is beyond the size of array you declared. Eventually, the function will come across a zero in memory somewhere and stop looking. If strcpy came across an unterminated string, it could copy hundreds of "characters" into the target character array before it found a zero—normally overwriting memory that does not belong to the target string. The results are usually catastrophic.

Getting Strings from the User


You can ask the user for a string. Using cin, you can get a single word (cin stops reading keyboard input after the first space) from the user and store it in a character array. Suppose that you defined a character array like this:


char input[80];

Using cin, the user can enter a string up to 79 characters (the extra character will hold the terminator) like this:


cout << "Please type the answer: ";  // Ask a question

cin >> input;   // Get a string from the user

The cout prompts the user to type something. Please remember that cin can get only one word at a time.

Visual C++ does not protect your string lengths! If you enter a string longer than 80 characters, you will not get an error, but important areas of memory might be overwritten and your computer can freeze up!

With user input, it is especially important to validate the input before using the data in your program. You might write a program that stores a user's name in a 20 character array; if a user types in a longer name, your program might receive more than 19 characters. You can use other string functions such as strlen to find out how long the string is, and first store the name in a very big character array before copying the name to your 20 character array (only if the name is less than 19 characters long). Although this might seem tedious, if you do not do it, the effect on your program will be disastrous.

Listing 6.4 contains a program that stores strings in four character arrays using the following methods:



Store strings in character arrays. Be sure to leave enough room for the terminator. There are several ways to store strings in arrays.

Input Listing 6.4. Storing strings in character arrays.

1:  // Filename: STR.CPP

2:  // Stores and initializes four character

3:  // arrays for three friends first names

4:

5:  #include <iostream.h>

6:  #include <string.h>

7:  void main()

8:  {

9:     // Declares all arrays and initializes the first one

10:    char friend1[20]="Lucy";

11:    char friend2[20];

12:    char friend3[20];

13:    char friend4[20];

14:

15:    // Uses a function to initialize the second array

16:    strcpy(friend2, "James");

17:

18:    friend3[0] = 'T';   // Initializes the third array

19:    friend3[1] = 'o';   // an element at a time

20:    friend3[2] = 'n';

21:    friend3[3] = 'y';

22:    friend3[4] = '\0';  // Without this, friend3 wouldn't

23:                        // hold a string

24:

25:    // Get a name from the user

26:    cout << "What is one of your friend's first name? ";

27:    cin >> friend4;

28:

29:    // Prints the names

30:    cout << friend1 << endl;

31:    cout << friend2 << endl;

32:    cout << friend3 << endl;

33:    cout << friend4 << endl;

34:    return;

35:  }

Output


What is one of your friend's first name? Marcia

Lucy

James

Tony

Marcia

Analysis

This program takes four character arrays and assigns them string values by using the four methods shown in this unit. Notice the extra #include file used with the string function strcpy().

Isn't the assignment of friend3, one element at a time, tedious? It is not used as often as the other methods of array initialization. strcpy() and other built-in string functions (all built-in string functions require #include <string.h>) are better to use. You will see many ways to initialize character arrays throughout this book.

Comparing cout and cin




cout and cin work to input and output data. You can format the output if you wish using I/O manipulators.

cout and cin are defined in IOSTREAM.H. As long as you include this header file, you can perform I/O with cout and cin. cout and cin are called objects. In Visual C++ terminology, an object is like a variable; in this case the data type is a file instead of an integer or character. You never treat cin and cout as variables, however. As far as you are concerned, you can think of cin as being the keyboard and cout as being the screen.

Use cout with the << operator and use cin with the >> operator. << is called the inserter operator because you are inserting to the screen (putting data there). >> is called the extractor operator because you are extracting from the keyboard (getting data from it).

As you've seen already in this unit, you often see cout and cin in pairs. For example, before asking the user for a value, you should prompt the user with a cout description of what you want. The following two lines tell the user what he or she is expected to type, and then wait for the user to type a number:


cout << "How much do you make? ";

cin >> Salary;   // Waits for the user to type a number


Can you see the flow of data in the >> and << operators? The direction of the arrows tells you which way the data is flowing: either to the screen or from the keyboard.


Output Options


The cout operator guesses how you want data printed. Sometimes, Visual C++ makes an incorrect guess as to how cout should produce a value, but most of the time cout suffices for any output you require, as shown here:


// cout can output integers:

cout << 45;   // Prints a 45

// cout can output floating-point values:

cout << 1.234567;   // Prints 1.234567

// cout can output string values:

cout << "I am learning C++";   // Prints I am learning C++

definition

An I/O manipulator modifies the way cout works.

Because Visual C++ can't always guess properly at how you want your data printed, you should learn a few of the I/O manipulators. Most of the time, you need a manipulator when you output numeric values. For instance, a float variable always contains six digits of precision. Therefore, when you print a float value, whether it is a literal or a floating-point variable, Visual C++ prints six digits. When you print a 4.5 like


cout << 4.5;

Visual C++ prints a 4.500000. The extra digits of precision often get in your way. You need a way to tell Visual C++ that you want only two digits of precision if you are printing a dollar value.

An output manipulator called precision() limits the precision of output printed with cout. Inside the precision() parentheses, you specify by integer literal or variable how many digits of precision you want to see in the output. To ensure trailing zeros, you must also set a cout flag. For instance, the cout


cout.setf(ios::fixed);       // Sets the cout flag for fixed-point

                             // non-scientific notation trailing zeros

cout.setf(ios::showpoint);   // Always shows decimal point

cout.precision(2);     // Two decimal places

cout << 4.5;

prints 4.50 on the screen. The cout.setf() is a strange-looking statement, and you will not fully understand the use of the periods and semicolons until later lessons on C++ objects. In the meantime, use the cout.setf() as described here and don't worry about the details at this point.



All subsequent couts retain the precision set with the last precision(). Think of precision() as being "sticky." Whatever precision you set sticks with the cout device until you change it with a subsequent precision() later in the program.

Perhaps, due to a user's bad answer, you want to get rid of anything else the user might have typed after the variable you have checked. (Recall that whitespace divides variables, but the input will not be read until the user presses the enter key.) Also, the user's carriage return might still be left in the input and you want to get rid of it. The following statement erases up to a maximum of 80 characters (more than enough in most instances) of input, up to and including the first newline encountered:


cin.ignore(80, '\n');  // Flush the input

The syntax for this statement is not the clearest in the world, but you'll only rarely need to use the ignore() function in this way. \n is the escape sequence for newline. Because there isn't a character on the keyboard that you can use for newline (pressing enter actually puts a newline in your code), C++ uses the backslash character to note that the following character is special, as you saw in the earlier section on escape code special characters.

If you have changed the precision with precision() and want to revert the precision to its default number of six places, either of the following statements works:


cout.precision(0);   // Resets to the default six places

or


cout.precision(6);   // Sets to the default six places

Visual C++ uses as much space as needed to print your numbers. For instance, it uses two output spaces to print a two-digit number, three output spaces for a three-digit number, and so on. You can use the () manipulator to add spacing to your output. The following cout statements show you what is possible with width():


cout.setf(ios::fixed);

cout.setf(ios::showpoint);

cout << 4.56  << endl;

cout.width(12);

cout << 4.56 << endl;

cout.width(8);

cout << "xyz" << endl;

cout.width(6);

cout << 12 << endl;

These four output commands produce the following output:


4.560000

    4.560000

     xyz

    12

Notice that each value prints within the width you specified.



The width() is the only manipulator that does not stick from one command to the next. Therefore, if you want to right-justify three numbers with a 10-space output width, you have to repeat width(), like this:

cout.width(10);

cout << 123 << endl;

cout.width(10);

cout << 12345 << endl;

cout.width(10);

cout << 1234567 << endl;

These three couts produce the following:

       123

     12345

   1234567

The width() is nice for aligning output. You can print data in tables in which all rows line up even if the data takes varying widths. This program prints a table of wins from the season of a local kids' soccer team. The numbers fall nicely beneath each team's name.


// Filename: TEAMMD.CPP

// Prints a table of team names and wins for three weeks

// using width-modifying conversion characters

#include <iostream.h>          

void main()

{

  cout.width(10);  cout << "Parrots"; 

  cout.width(10);  cout << "Rams";

  cout.width(10);  cout << "Kings";

  cout.width(10);  cout << "Titans";

  cout.width(10);  cout << "Chargers" << endl;

  cout.width(10);  cout << 3;

  cout.width(10);  cout << 5;

  cout.width(10);  cout << 2;

  cout.width(10);  cout << 1;

  cout.width(10);  cout << 0 << endl;

  cout.width(10);  cout << 2;

  cout.width(10);  cout << 5;

  cout.width(10);  cout << 1;

  cout.width(10);  cout << 0;

  cout.width(10);  cout << 1 << endl;

  cout.width(10);  cout << 2;

  cout.width(10);  cout << 6;

  cout.width(10);  cout << 4;

  cout.width(10);  cout << 3;

  cout.width(10);  cout << 0 << endl;

  return;

}

Here is the program's output:


Parrots      Rams     Kings    Titans  Chargers

      3         5         2         1         0

      2         5         1         0         1

      2         6         4         3         0


If you are an advanced programmer and you want to print a number in hexadecimal or octal, insert the hex or oct manipulator in the cout output. The result will appear in base-16 or base-8, respectively. To revert to decimal, insert the dec manipulator in the output before the decimal value prints.


Input Options


The cin acts like your keyboard, and combined with the >> operator, cin pauses your program and waits for the user at the keyboard to enter data. With a single cin, you can get one or more values (just as with cout you can display one or more values), as long as you separate the values in the cin with extra >> operators.

The following statement gets input from the user into a variable named Result:


cin >> Result;   // Lets the user type a value into Result


The User Makes Mistakes!

Will the user always type exactly what he or she is supposed to type? Think of the times you have visited an automatic teller. Did you ever press the wrong button? Most people do at one time or another. Usually, you can correct your mistake or cancel the operation and start over. When you write programs that require user input, you must be aware that the user—either intentionally or unintentionally—might not follow directions.

When you want an integer, the user might type a floating-point value. With simple cin statements, there is little you can do except check the data that the user entered to see whether it is reasonable and whether it falls within certain expected ranges.


The problem of getting multiple values with cin is further hindered by the fact that the user must type a whitespace character between the values. In Visual C++ terminology, a whitespace character is any space, Tab keystroke, or Enter keystroke. Therefore, in response to the statement


cin >> a >> b >> c;   // Gets three values from the keyboard

the user can enter three values separated by a space:


5 7 9

Or the user can press the Tab key:


5    7    9

Or the user can press Enter at the end of each value:


5

7

9

In all three cases, the program will store a 5 in a, a 7 in b, and a 9 in c.

It might seem that with all those choices, the user has freedom to do whatever seems most comfortable. The only problem is that there are many typing choices that the user might make that do not work. For example, what do you think will happen if the user types the following line?


5, 7, 9

The Visual C++ program does not consider a comma to be a whitespace character. Therefore, only the 5 is correctly put in a, and the other two variables will have garbage in them.

There is little you can do to control the user, but you can tell the user exactly what you want to see as input with a prompt message before each cin:


cout << "Please type three numbers.  Separate the three" << endl;

cout << "values with a space and do not use a period in ";

cout << "the numbers." << endl;

cin >> a >> b >> c;

It is even safer to stay away from multiple variables with cin. Instead of getting all three in one input, it might be better to get them one at a time, prompting the user along the way:


cout << "What is the first value?  (Please, no decimal ";

cout << "points)" << endl;

cin >> a;

cout << "What is the second value? ";

cin >> b;

cout << "What is the last value? ";

cin >> c;

In typical programming, you would be asking for input that the user understands, such as "What is your result?" or "How old are you?"

Getting Lines of Data


If you need to get a line of input, the getline() function is the right choice. getline() is useful when you want the user to enter a string of data into a character array. Whereas cin stops reading input when it gets to the first space, getline() ends only after the user presses the Enter key. Whatever the user typed up to that point goes to the character array.

There are several forms of getline(), but the most common one looks like this:


cin.getline(chararray, num);

The chararray is any character array you defined earlier that holds the input string. The num is the maximum number of characters you want to read with getline(). The cin. in front of getline() might look strange to you. cin. is not part of the getline() name. Rather, you are telling the cin object to go get a line from the keyboard. You do not have to understand object-oriented programming to understand getline(), but as soon as you have learned object-oriented concepts (explained in the last lessons in this book), you will see why cin and getline() are separated by a period.

getline() always stops reading the user's input when the maximum number of characters is entered. getline() also ensures that there is always room for a string-terminating zero. Therefore, if the user types exactly the same number of characters as the maximum number getline() allows, Visual C++ replaces the last character with a string terminator, thereby ensuring that the input is made into a string. (The newline keystroke is never stored in the string.)

If you want to correctly validate the input, getline() is more powerful than using the cin inserter. In later lessons, you will learn programming techniques that enable you to examine what the user has typed and handle the user's errors in a more professional way.

In the following program, the user can enter a two-word city name in response to the cout prompt:


// Filename: GETL.CPP

#include <iostream.h>

void main()

  {

    char city[15];

    cout << "Where are you from? ";

    cin.getline(city, 15);

    cout << "So you are from " << city << endl;

    return;

  }

Here is the output:


Where are you from? Los Angeles

So you are from Los Angeles

Performing input and output is extremely easy with Visual C++. You need a way to get data and results of calculations to the screen and to get input from the user at the keyboard. This book has already used cout and cin for simple input and output. This unit reviewed cout and cin, and then explained how to make them work exactly the way you want them to.

Listing 6.5 contains a program that gets and prints a floating-point variable and a character array.



Use getline() to get strings from the user. cin without the getline() does not get more than one word at a time.

Input Listing 6.5. Getting an inventory item's price and description.

1:  // Filename: INVENT2V.CPP

2:  #include <iostream.h>

3:  

4:  void main()

5:  {

6:

7:    // Define the two inventory variables

8:    float price;

9:    char descrip[25];

10:

11:    cout << "What is the item's description? ";

12:    cin.getline(descrip, 25);

13:

14:    cout << "What is the item's price? ";

15:    cin >> price;

16:

17:    cout << endl << endl "Here is the item:" << endl

18:    cout << "  Description: " << descrip;

19:

20:    cout.precision(2);

21:    cout.setf(ios::fixed);

22:    cout.setf(ios::showpoint);

23:    cout << "  Price: " << price << endl

24:    return;

25:  }

Output


What is the item's description? Large Widgets

What is the item's price? 3.44

Here is the item:

Description: Large Widgets

Price: 3.44

Analysis

A 25-character array is defined in line 9, and the getline() in line 12 gets the value of the array from the user. After the price is entered in line 15, the data is printed back again in lines 17 through 23.

Lines 20, 21, and 22 ensure that two decimal places, no more and no fewer, will print for the price. Without these I/O manipulators, the price would print with six decimal places.

Homework



General Knowledge


  1. Which of the following are string literals, which are character literals, which are numeric literals, and which could be variable names?

    
    Hi
    
    'H'
    
    "56"
    
    '2'
    
    "hi"
    
    '1'
    
    1

  2. What is another name for a string terminator?

  3. Where is the string terminator in this string?


    
    "000000000"

  4. What symbol is the extractor operator, and does cin or cout go with it?

  5. What symbol is the inserter operator, and does cin or cout go with it?

  6. What is the advantage of using getline() rather than cin when getting strings of user input?

  7. What does the number in getline() do?

  8. Using the ASCII table in Appendix B, write the decimal ASCII numbers for each of the characters in the following string.


    
    "I'll take 10."

  9. What is the length of this string? Hint: There is a difference between a character 0 and the string-terminating zero.


    
    "That costs 50"

  10. Using the ASCII table in Appendix B, write a line that assigns an upside-down question mark to a character variable named q.

  11. How many elements are reserved in the following character array?


    
    char MyAddress[25];   // Defines room for an address

  12. How many characters will C++ reserve in the following array definition?


    
    char movie[] = "Cinema Fantastico";

  13. Which I/O manipulator limits the number of decimal places printing when you output floating-point data?

  14. What header file must you include when you use the I/O manipulators?

  15. Does a character array always hold a string? Why or why not?

  16. True or false: cout is useful for inputting lines of input, such as a user's street address.

  17. True or false: These are exactly the same thing in Visual C++:

    
    "C" and 'C'

    What's the Output?


  18. What will the following four couts print?

    
    cout << 4.5 << " ";
    
    cout.precision(1);
    
    cout << 4.5 << " ";
    
    cout << 4.5 << endl;

  19. What does the following print, assuming that name holds "Jane Larson"?
    
    cout << name[3] << name[5] << name[6]
    
         << name[7] << name[8] << "." << endl;

  20. What is the output of the following program? (Assume that the user enters The Italian Riviera for the title.)

    
    #include <iostream.h>
    
    void main()
    
    {
    
       char title[19];
    
       cin.getline(title, 19);
    
       cout << title << endl;
    
    }

  21. What value is in c when these two lines finish executing?
    
    int c;
    
    c = 'A' + 5;   // Adds 5 to the ASCII character

    Find the Bug


  22. The following cout has a problem. What is it?


    
    cout << 'ABC';   // Almost works

  23. The following cout statement attempts to send a single quotation mark to the screen. It tries to specify the single quotation mark as a character literal, but Visual C++ balks at '''. What is another way to designate and output a single quotation mark?


    
    cout << ''';   // Attempts to output a single quotation mark

  24. What is wrong with the following program?
    
    #include <iostream.h>
    
    void main()
    
    {
    
      char addr[25];
    
      strcpy(addr, "35 W. Hazelnut");
    
      cout << "My address is " << addr;
    
    }

  25. The following program is supposed to ask for a user's age and then display that age in dog years (to make the user feel younger). Something is wrong. Can you spot it?

    
    #include <iostream.h>
    
    void main()
    
    {
    
      int age, dogage;
    
      cout >> "How old are you? ";
    
      cin << age;
    
      dogage = age / 7;   // Converts to a dog's age
    
      cout >> "In dog years, you are " >> dogage >> "years old.";
    
    }

  26. Using cout, a programmer wants to print three people's names, each stored in character array variables. The programmer wants the names to start printing every 15 columns. The following cout will not do it. Why?

    
    cout.width(15);
    
    cout << name1 << name2 << name3;   // Invalid

    Write Code That. . .


  27. How would you define and initialize a character array that is 20 characters long and holds the company name "Widgets, Inc."?

  28. Write a program that asks the user for his or her first and last name. Print the names as they would appear in a phone book. In other words, if the user enters Mary Freeman for the first and last name, finish the program so that it prints this:


    
    In a phone book, your name would look like this: Freeman, Mary

    Extra Credit



  29. Nancy Foster, a computer sales representative for HAL Computers, Inc., wants to know her average monthly sales for the previous 12 months. Write a program that asks her for each of the sales values and prints an average of them on the screen.

Previous Page Page Top TOC Next Page