More C++ Basics
Basic Elements of C++ (Part 3)
This 32-minute video is an overview of the third part of Chapter 2.
String Variables and String Input
Click me to view the code from the video.
cpp
/*
* A game where the user is prompted to enter different types of
* words that are then substituted into a story for comedic effect.
*
* by Dr. Hayes
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Define variables
string color, jobTitle, event, action;
int age;
// Get words to substitute into story
cout << "Enter a color: ";
cin >> color;
cout << endl;
cout << "Enter an occupation: ";
cin >> jobTitle;
cout << endl;
cout << "Enter a weather event: ";
cin >> event;
cout << endl;
cout << "Enter a whole number: ";
cin >> age;
cout << endl;
cout << "Enter a progressive-tense action (ending in \"ing\"): ";
cin >> action;
cout << endl;
// Tell the story.
cout << "[" << color << "]beard, was a pirate who operated around "
<< "the CSU campus.\n"
<< "Little is known about his time as a ["
<< jobTitle << "], but he was a sailor during the great ["
<< event << "]. Placed in command by Captain Bucky, ["
<< color <<"]beard at the age of [" << age
<< "] engaged in numerous acts of [" << action
<< "]. After his death, he became the inspiration"
<< " for a [" << jobTitle << "] in works of fiction across "
<< "many genres." << endl;
return 0;
}What Is a string?
A string is a variable type used to store text data, such as words, sentences, or any sequence of characters.
Examples:
"Hello""CS101""123 Main Street"
In modern C++, strings are typically handled using the Standard Library type string.
Including and Using string
To use string, you must include the <string> header.
cpp
#include <string>
using namespace std;Declaring and Initializing Strings
cpp
string name;
string city = "Charleston";
string greeting {"Hello"};
// You can also assign a value later
name - "Alice"Strings vs. Characters
A character uses type char and stores a single character:
cpp
char letter = 'A';A string stores multiple characters:
cpp
string word = "Apple";Key difference:
- char uses single quotes:
'A' - string uses double quotes:
"A"
Input with Strings
cin reads input up to the first whitespace.
For example, if the user input for the following code is John Smith, the value stored in firstName is "John".
cpp
string firstName;
cout << "Enter Your Name: ";
cin >> firstName;
cout << '\n';Outputting Strings
Strings are printed using cout like any other variable.
cpp
cout << "Hello, " << firstName << "!" << endl;