PROGRAMMING
PROGRAMMING
C++
It is up to you whether you want to use + or append().
C++ Strings The major difference between the two, is that the
• Strings are used for storing text. append() function is much faster. However, for testing
and such, it might be easier to just use +.
• A string variable contains a collection of characters
surrounded by double quotes:
string greeting = "Hello"; C++ uses the + operator for both addition and
concatenation.
To use strings, you must include an additional header
file in the source code, Numbers are added. Strings are concatenated.
the <string> library: If you add two numbers, the result will be a number:
Example
You can access the characters in a string by referring to However, cin considers a space (whitespace, tabs, etc.)
its index number inside square brackets []. as a terminating character, which means that it can only
display a single word (even if you type many words):
This example prints the first character in myString:
From the example above, you would expect the
Example:
program to print
string myString = "Hello";
"John Doe", but it only prints "John".
cout << myString[0];
That's why, when working with strings, we often use the
// Outputs H getline() function to read a line of text. It takes cin as
the first parameter, and the string variable as second:
Example
This example prints the second character in myString:
string fullName;
Example
cout << "Type your full name: ";
string myString = "Hello";
getline (cin, fullName);
cout << myString[1];
cout << "Your name is: " << fullName;
// Outputs e
// Type your full name: John Doe
Example: You might see some C++ programs that runs without
the standard namespace library. The using namespace
string myString = "Hello"; std line can be omitted and replaced with the std
myString[0] = 'J'; keyword, followed by the :: operator for string (and
cout) objects:
cout << myString;
Example:
// Outputs Jello instead of Hello
#include <iostream>
#include <string>
User Input Strings
int main()
It is possible to use the extraction operator >> on cin to
display a string entered by a user: {
cout << "Your name is: " << firstName; It is up to you if you want to include the standard
namespace library or not.
// Type your first name: John
C++ Math
C++ Math
Example:
Example
Example:
#include <cmath>