## Highlights of this lab:

In this lab, you will practice on:

## In-Lab Exercise:

Click the little computer above for a detailed description.

If you need help during the week, you are welcome to go to CL119 during Office Hours posted for lab instructors.

Back to Highlights

## Strings

A string may be defined without an initializing value, in which case its initial value is an empty string (zero length, no characters):

```    string str1;

A string object may also be initialized with

* a string expression:

string str2 = str1;
string str3 = str1 + str2;

* a character string literal:

string str4 = "Hello there";
string str5 ("Goodbye");  // Alternate form

* a substring of another string object:

string str8 = "ABCDEFGHIJKL";
// Initialize str9 as "CDEFG"
// Starts at character 2 ('C')
// with a length of 5
// (or the rest of the string, if shorter)
string str9 (str8,2,5);

```

### The length and size Functions

```Both of these functions return the length (number of characters) of the string. The
size_type return type is an unsigned integral type. We must use the qualified name
as in string::size_type because the definition of size_type is otherwise hidden
inside the definition of the string type.

string str = "Hello";
string::size_type len;
len = str.length(); // len == 5
len = str.size();   // len == 5

or you can just use cout << str.length() << endl;

```

### The find and substr Functions

```size_type find (str, size_type pos);
Search for the first occurrence of the substring str in the current string, starting at
position pos. If found, return the position of the first character. If not, return a
special value (called string::npos).

string str16 = "abcdefghi";
string str17 = "def";
string::size_type pos = str16.find (str17,0);
cout << pos << endl; // return 3
pos = str16.find ("AB",0);

string substr (size_type pos, size_type n);
Returns a substring of the current string, starting at position pos and of length n:

string str18 = "abcdefghi"
string str19 = str18.substr (6,2);
cout << str19 << endl; // return "gh"
```

### Operators

A number of C++ operators also work with strings.

• The assignment operator = may be used in several ways:
```

Assigning one string's value to another string
string string_one = "Hello";
string string_two;
string_two = string_one;
Assigning a single character (char) to a string
string string_four;
char ch = 'A';
string_four = ch;
string_four = 'Z';

```
• The "plus" operator concatenates:
```
two strings string str1 = "Hello ";
string str2 = "there";
string str3 = str1 + str2; // "Hello there"

a string and a character string literal
string str1 = "Hello ";
string str4 = str1 + "there";

a string and a single character
string str5 = "The End";
string str6 = str5 + '!';

```
• The "+=" operator
```combines the above assignment and concatenation operations in the way that
you would expect, with a string object, a string literal, or a single
character as the value on the right-hand side of the operator.

string str1 = "Hello ";
str1 += "there";

```
Back to Highlights

## Input Stream

To get data into programs, there are two ways to do it: First, we use istream variable cin together with the extraction operator >> to get data from the standard input device --- keyboard. The other way is to get data from a file to the program. We will talk about that later in the next section.

Here is the syntax template for an input statement

```cin >> Variable >> Variable ...;
```
When you enter input data at the keyboard, you must be sure that each data value is appropriate for the data type of the variable in the input statement.

The >> operator skips any leading white space characters when it is looking for the next input value in the stream. Whitespace characters are blanks and certain nonprintable characters such as the character that marks the end of a line (new line character). After skipping any whitespace characters, >> operator proceeds to extract the desired data value from the input stream. If the data value is int or float, input of the number stops at the first character that is inappropriate for the data type, such as a whitespace character. If the data value is a char value, input stops as soon as a character is input. But the get function from istream data type works a little differently. It inputs the next character in the stream regardless of what it is, even if it is a whitespace character or new line character. Now look at the following two examples. Compile and run them with the same set of the input data. e.g. (a b c d or a 2bc). Examine the results carefully.

```
// from the keyboard and then prints them.

#include <iostream>
using namespace std;

int main ()
{
char  char1;
char  char2;
char  char3;
char  char4;

cout  << "Input four characters.  Press Return."  << endl;
cin  >> char1  >> char2  >> char3  >> char4;
cout  << char1  << char2  << char3  << char4;
return 0;
}

```
```
// Program Char2Rd prompts for and reads four characters
// from the keyboard and then prints them.            *)

#include <iostream>
using namespace std;

int main ()
{
char  char1;
char  char2;
char  char3;
char  char4;

cout  << "Input four characters.  Press Return."  << endl;
cin.get(char1);
cin.get(char2);
cin.get(char3);
cin.get(char4);
cout  << char1  << char2  << char3  << char4;
return 0;
}

```
Now the last thing to emphasize. For a string variable, say inputStr, the statement
```cin >> inputStr;
```
skips leading whitespace and it stops as soon as it encounters a whitespace character. The statement
```getline(cin, inputStr);
```
does not skip the leading whitespace character(s). It stops when a new line character '\n' is encountered. getline is a function from C++ standard library.

## File Input and Output

If you want to prepare input data ahead, you may store the data in a file and direct the program to read its input from a file. If you want to save output data in a file to use later, you may direct the program to write to a file. To read and/or write to a file, do the following:
1. Request the preprocessor to include file fstream as well as iostream. fstream contains the declarations for defining input and output streams with files other than cin and cout.
2. Declare an input stream to be of type ifstream or an output stream to be of type ofstream.
3. Prepare the stream for use by using the function named open provided in file fstream. The parameter for the function open is the external name of the file. The external name is the name under which the file is stored on the disk.
4. Put the internal file name to the left of the insertion or extraction operator.

Here is an example program that reads four floating point data values from a file and writes to another file in the reverse order.

```
// Program IODemo demonstrates how to use files

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

int main()
{
cout  << fixed  << showpoint;
//sets all printout in decimal format with decimal points appearing

float val1, val2, val3, val4;	// declares 4 variables
ifstream inData;			// declares input stream
ofstream outData;			// declares output stream

inData.open("Data.In");
// binds program variable inData to file "Data.In"

outData.open("Data.Out");
// binds program variable outData to file "Data.Out"

inData  >> val1 >> val2 >> val3 >> val4;	// inputs 4 values
outData  << val4  << endl;
outData  << val3  << endl;
outData  << val2  << endl;
outData  << val1  << endl;	// outputs 4 values
return 0;
}

```
Each file in your program has both an internal name and an external name. The internal name is what you call it in your program; the external name is the name the operating system knows it by. Somehow, these two names must be associated with one another. This association is called binding and is done in function open. Notice that inData and outData are identifiers in the program; "Data.In" and "Data.Out" are character strings. Data.In is the name that was used when the input data file was created; Data.Out is the name of the file where the answers are stored.

You will need to use the pico or vi text editor to create the input data file according the requirement of the data type and format in your program. The input data file must exist and contain correct data. Otherwise, the input will fail.

For example, in the preceding IODemo program, the input file should look like this:

```5.5
6.6
7.7
8.8
```
You may run the program and experience how File I/O works.

## In-Lab Exercise:

Click on the little computer for detailed description.