Objective #1: Understand strings.
- A string is a sequence of characters that may or may not spell
a word.
- A string literal is a sequence of characters that is used in
a C++ program between double quotes such as in the statement
cout << "Hello world!";
where "Hello world!" is the string literal. Note that the
string literal, in this case, includes a space and an exclamation point.
Objective #2: Use string variables.
- When one needs to refer to a variable that contains multiple characters,
he or she needs to use a string variable.
- You must declare a string variables with declaration statements such as:
string
name;
string
name = "John Doe";
string name = "";
Notice in the last example, the null string "" (aka empty string) is stored in the variable name.
- You can use the assignment operator to assign the value of a string literal to a string as in
name = "Santa Claus";
or you can assign one string variable to another string variable as in
name = personName;
- In order to use string variables, you must use
the compiler directive,
#include <string>
at the top of your program. The following program uses a string variable and properly includes the
necessary header files,
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cin >> name;
cout << name;
return 0;
} // end of main
Objective #3: Understand the length function, string concatenation,
and relational operators with string variables.
- You can determine the current length of a string with the use of a
string's length function. For
example,
string name = "Bill";
int lengthOfName = 0;
lengthOfName = name.length();
cout << "His name is " << lengthOfName <<
" letters long.";
- Do not forget to type the empty parentheses after the length
function.
- To compare two strings in order to see if they are exactly the same,
you can use the Boolean == operator.
For example,
if (string1 == string2)
{
cout << "The strings are the same!\n";
}
causes the message to be printed on the screen if the two strings, string1 and string2, are equivalent.
- Each letter has a specific ASCII value (also known as a Unicode value.) Consult an ASCII chart (e.g. asciichart.com ) for this universally accepted set of numbers since it applies to all operating systems and computer platforms not just Microsoft Windows or C++. For this CMPSC 101 class you should memorize the values for the uppercase letter A which has an ASCII value of 65 and a lowercase a which has an ASCII value of 97. You should also know that a blank space has an ASCII value of 32. By memorizing those values you can easily figure out any other letter in the alphabet since the letters B through Z are consecutively numbered from 66 on and the lowercase letters b through z are numbered 98 on.
- You can also test two strings alphabetically using the < or > operators.
For example,
string1 = "aardvark";
string2 = "zebra";
if (string1 <
string2)
{
cout << "string1 comes before string2
alphabetically ";
}
The first a in "aardvark" is compared to the z in "zebra" and since the ASCII value of a is less than the ASCII value of z then string1 is considered less than string2 even though the length of "zebra" is less than the length of "aardvark".
Here are some other string comparisons
"abc" is less than "abcd"
"aardvark" is less than "aardvarks"
"Zeus" is less than "aardvark"
"aardvark" is less than "zeus"
" zeus" is less than "aardvark" (note that there is a blank space in front of the z in " zeus"
- To combine two strings into one larger string is called concatenation.
To concatenate two string variables, you can use the concatenation
operator (+). For example,
firstName = "John";
lastName = "Doe";
cout << firstName
+ lastName;
would display the string literal "JohnDoe".
Objective #4: Use subscript notation to access individual characters
within a string variable.
- C++ numbers the individual characters in a string beginning with index
position 0. So after the declaration statement,
string name = "frank jones";
is made, the 'f' is considered to be in the index position 0, the
'r' in index position 1, the 'a' in index position 2, and so
on. Note that the index position 5 contains a blank space, which is,
of course, a valid character.
- You can use subscript notation to display one specific letter of a string as in
cout << name[0];
which displays the first letter of the string name.
- You may use subscript notation
to change the value of one specific character within a string. The assignment
statement,
name[0]
= 'F';
would change the lowercase f originally found in index
position 0 of the example above to an uppercase F. So the string is
now "Frank jones".
- By using subscript notation along with the length function, you can display or change the very last letter of a string no matter how long it is. Review the following example
name = "frank jones";
name[name.length() - 1] = 'z';
cout << name[name.length() - 1];
displays the letter z since the string name has been changed to "frank jonez".
PSU Berks CMPSC 101 students will not be tested on the notes below.
Objective #5: Use the getline function.
- In order to allow the user to enter a whole
name (or any combination of two or more words separated by blank spaces),
you must use the getline function. By using the getline function, everything that the
user types until he/she presses the Enter key is stored in a specified
string variable.
- The following example would allow a whole name such as "John
Doe" to be stored in the string variable name.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
getline(cin, name);
cout << name;
return 0;
} // end of main
- If a cin input statement precedes your getline statement, you may need to use the ignore function to "flush the buffer" and get rid of any extra new
line characters that the user inputed when he or she inputed a previous
value.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age;
string name;
cout << "Enter your age: ";
cin >> age;
cin.ignore(100, '\n');
cout << "Enter your full name:
";
getline(cin, name);
cout << name;
return 0;
} // end of main
The cin.ignore statement tells the
compiler to ignore the next 100 characters or everything entered up
to the next press of the Enter key. I use 100 characters simply because
that is usually enough characters to ignore and more importantly it
is only the extra press of the Enter key that we need to ignore after
a cin statement and it is ignored by
including the \n parameter.
- There is actually a bug in Visual C++ that forces users to input
an extra Enter key or two when getline is used in a program. See these
pages for details of this bug and a solution:
http://www.cs.drexel.edu/~mcs171/Sp03/extras/getline_Fixer/instructions.html
and
http://support.microsoft.com/default.aspx?scid=KB;EN-US;q240015
Objective #6: Use character arrays.
- A character array can be declared with a statement like
char word[10];
that allows for words up to 9 letters long. The last position of a character array stores the null terminator (\0) and cannot be used to store a meaningful letter or character. Character arrays are sometimes called c-strings.
- You can also declare a character array with a string literal value but in that case you should not specify the size of the character array as in
char word[] = "hello";
The size of the character array is 6 since a null terminator is automatically added to the last position of the array.
- Like string variables, you can display and/or access a single letter of a character array by using the square brackets as in
cout << "The third letter of the word is " << word[2] << endl;
Keep in mind that the first letter of a character array is considered to be in position 0 of the array.
- You can convert a string into a character array using the c_str method as in
char word[10];
string input = "hello";
word = input.c_str();
- You can convert a number that is saved as a character array into a string variable with the atof function as in
double num = 0;
num = atof("123.45");
or
char userInput[] = "123.45";
num = atof(userInput);