Strings
- Strings are a collection of 0 or more characters.
- Strings are not part of core c++
- They are part of the standard library.
- You need
#include <string>
to use them.
-
string
is not a reserved word.
- Strings are an object
- They initialize themselves to the empty string "".
- They have other methods as well.
- String Input
-
cin >> aString
will
- skip all whitespace.
- read in all contiguous non-whitespace characters and store them in aString
- stop when a whitespace character is encountered.
-
getline(stream, string)
will
- Read in and store all characters until a newline (\n) is encountered.
- The newline is read, but thrown away.
- Ignoring Input
-
cin.ignore(length, del)
- length is the maximum number of characters to ignore
- del is the character to stop ignoring.
- It trows away all input characters until either
- length characters have been read
- OR the del character is read.
-
cin.ignore(1000, '\n')
is the common usage.
- If you want a single word
- If you want to read in multiple words at once
- use
getline(cin, stringvar);
- BUT BE AWARE OF ANY READS that WENT BEFORE.
- You may need a
cin.ignore(1000, '\n');
- String concatenation
- The + operator concatenates two strings.
-
fullName = firstName + lastName
- It
- creates a new string
- copies all of the letters from the first string to the new string.
- copies all of the letters from the second string to the new string.
- Write a program that
- Asks the user for a single word family name.
- The asks the user for other names.
- Constructs a single full name and prints it out.
- Finish our Grandmother's Trunk example.